首页 > 代码库 > jdk动态代理实现
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动态代理实现
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。