动态代理中的静态 invocationhandler
在使用 jdk 动态代理时,某些场景需要在 invocationhandler 中使用静态方法。然而,这种做法可能会带来潜在的隐患。
以下是使用静态方法的示例代码:
class myinvocationhandler implements invocationhandler {
private static service targetservice;
@override
publi
c object invoke(object proxy, method method, object[] args) throws throwable {
return null;
}
public static service getproxyservice(service target) {
targetservice = target;
classloader contextclassloader = thread.currentthread().getcontextclassloader();
class>[] interfaces = targetservice.getclass().getinterfaces();
return (service) proxy.newproxyinstance(contextclassloader, interfaces, new myinvocationhandler());
}
}使用静态方法的潜在隐患在于:
因此,推荐使用匿名内部类来实现 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;
}
});