Skip to content

Instantly share code, notes, and snippets.

@zhanggang807
Last active January 10, 2018 07:33
Show Gist options
  • Save zhanggang807/66601644f2e48949e08986909e461df6 to your computer and use it in GitHub Desktop.
Save zhanggang807/66601644f2e48949e08986909e461df6 to your computer and use it in GitHub Desktop.
dynamic proxy of JDK
public interface Service {
//目标方法
public abstract void add();
}
class UserServiceImpl implements Service {
public void add() {
System.out.println("This is add service");
}
}
class MyInvocatioHandler implements InvocationHandler {
private Object target;
public MyInvocatioHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("-----before-----");
Object result = method.invoke(target, args);
System.out.println("-----end-----");
return result;
}
public Object getProxy() {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Class<?>[] interfaces = target.getClass().getInterfaces();
return Proxy.newProxyInstance(loader, interfaces, this);
}
}
class ProxyTest {
public static void main(String[] args) {
Service service = new UserServiceImpl();
MyInvocatioHandler handler = new MyInvocatioHandler(service);
Service serviceProxy = (Service) handler.getProxy();
serviceProxy.add();
}
}
//参考资料
//http://mp.weixin.qq.com/s?__biz=MzIwMzY1OTU1NQ==&mid=2247483854&idx=1&sn=3dea3d634e99bae34978c544852a08a8&chksm=96cd4182a1bac894c3ce652396b32e9663f421bd4aeb5532c6b9d9ada6d194a1d5b22ea6b535&scene=21#wechat_redirect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment