JDK实现动态代理基本就两步:
- 调用Proxy#newProxyInstance(…)方法,传入所需参数
- 定制需要对被代理对象进行操作的InvocationHandler实现类
需要被代理的接口
public interface MyInterface {
void sayHello(String str);
}
代理操作
public class testJDK {
public static void main(String[] args) {
MyInterface impl = (MyInterface)Proxy.newProxyInstance(MyInterface.class.getClassLoader(),
new Class[]{MyInterface.class},
new sayHelloInvocationHandler());
impl.sayHello("hello");
}
}
class sayHelloInvocationHandler implements InvocationHandler{
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println(args);
System.out.println(args[0]);
// 使用Proxy#newProxyInstance(...)方法传入的类不是可实例化的时候(接口或抽象类),
// 不能调用method#invoke(...) 方法
// method.invoke(args[0]); object is not an instance of declaring class
return null;
}
}