JDK动态代理
固定的Proxy.newProxyInstance()方法
package shejimoshi.dongtaidaili;
import java.lang.reflect.Proxy;
public class JDKProxyFactory {
public Object getProxy(Object target) {
Object proxy = Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),new MyInvocationHandler(target));
return proxy;
}
}
主要想增强的代码逻辑在这里写
package shejimoshi.dongtaidaili;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class MyInvocationHandler implements InvocationHandler {
private Object target;
public MyInvocationHandler(Object object) {
this.target = object;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//增强代码逻辑(执行代码前)
System.out.println("执行方法前");
//xxx
Object returnValue = method.invoke(target, args);
//增强代码逻辑(执行代码后)
//xxx
System.out.println("执行方法后xxxxxxx");
return returnValue;
}
}
使用示例
前提准备接口
package shejimoshi.dongtaidaili.demo;
public interface StudentService {
public void sayHello();
}
前提接口实现类
package shejimoshi.dongtaidaili.demo;
public class StudentServiceImpl implements StudentService{
public void sayHello() {
System.out.println("说 hello");
}
}
测试类
package shejimoshi.dongtaidaili.demo;
import shejimoshi.dongtaidaili.JDKProxyFactory;
public class UseDemo {
public static void main(String[] args) {
StudentService studentService = new StudentServiceImpl();
JDKProxyFactory proxy = new JDKProxyFactory();
StudentService proxyService = (StudentService) proxy.getProxy(studentService);
proxyService.sayHello();
}
}
输出
执行方法前
说 hello
执行方法后xxxxxxx