jdk动态代理实现
Posted smilemyf
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jdk动态代理实现相关的知识,希望对你有一定的参考价值。
1、jdk动态代理的简单实现类
package com.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class JDKProxy implements InvocationHandler{ private Object target;//目标对象 public JDKProxy(Object target) { super(); this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("--------------------invoke-before----------------------"); Object object = method.invoke(target, args); System.out.println("--------------------invoke-after----------------------"); return object; } public Object getProxy(){ return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this); } }
2、测试用接口和接口实现
package com.proxy.manager; public interface HelloWorldManager { public void sayHello(); }
package com.proxy.manager.impl; import com.proxy.manager.HelloWorldManager; public class HelloWorldManagerImpl implements HelloWorldManager { @Override public void sayHello() { System.out.println("Hello World!"); } }
3、测试类
package com.proxy.test; import com.proxy.JDKProxy; import com.proxy.manager.HelloWorldManager; import com.proxy.manager.impl.HelloWorldManagerImpl; public class JDKProxyTest { public static void main(String[] args) { HelloWorldManager hw = new HelloWorldManagerImpl(); JDKProxy jdkProxy = new JDKProxy(hw); HelloWorldManager hellWorldManager = (HelloWorldManager) jdkProxy.getProxy(); hellWorldManager.sayHello(); } }
4、测试输出接口
--------------------invoke-before---------------------- Hello World! --------------------invoke-after----------------------
以上是关于jdk动态代理实现的主要内容,如果未能解决你的问题,请参考以下文章