1. 需要一个接口,用于定义被代理的行为。不使用接口不行。
2. InvocationHandler接口的invoke方法有3个参数,分别是被代理对象、被执行的接口方法、方法参数
3. Proxy.newInstance的参数分别是被代理对象的类加载器、接口、InvocationHandler实例
public class MyInvocationHandler implements InvocationHandler {
private Object target;
public MyInvocationHandler() {
super();
}
public MyInvocationHandler(Object target) {
super();
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before...");
method.invoke(target, args);
System.out.println("after...");
return null;
}
public static void main(String[] args) {
TestService myopt = new MyOpt();
InvocationHandler handler = new MyInvocationHandler(myopt);
TestService opt = (TestService) Proxy.newProxyInstance(myopt.getClass().getClassLoader(),
myopt.getClass().getInterfaces(), handler);
opt.test();
}
public interface TestService {
default void test() {
System.out.println("接口");
}
}
public static class MyOpt implements TestService {
}
}