java动态代理中,invocationhandler中的静态方法的隐患
在java动态代理中,invocationhandler负责处理被代理对象的方法调用。如果invocationhandler中包含静态方法,可能会存在一些隐患。
以给出的代码为例:
class myinvocationhandler implements invocationhandler {
private static service targetservice;
@override
public object invoke(object proxy, method method, object[] args) throws throwable {
return null;
}
public static service getproxyservice(service target) {
targetservice = target;
// 执行动态代理相关操作
return (service) // ...
}
}其中,targetservice是一个静态变量,这会导致一些问题:
为了避免这些隐患, рекомендуется使用匿名内部类实现invocationhandler,因为它没有静态字段:
Service proxyInstance = (Service) Proxy.newProxyInstance(target.getClass().getClassLoader(),
target.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if ("add".equals(method.getName())) {
System.out.println("HELLOIDEA");
}
return null;
}
});
proxyInstance.add();