关于jdk 动态代理 如果InvocationHandler中用静态方法有没有什么隐患

2019-01-02 20:07发布

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;
    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    Class<?>[] interfaces = targetService.getClass().getInterfaces();
    return (Service)Proxy.newProxyInstance(contextClassLoader,interfaces,new MyInvocationHandler());
}

}

1条回答
弹指情弦暗扣
2楼-- · 2019-01-02 21:01

还是直接用匿名内部类吧
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();

查看更多
登录 后发表回答