首页 > 代码库 > 动态代理
动态代理
public interface Subject{ public void dosomething(String str); } public class RealSubject implements Subject { @Override public void dosomething(String str) { System.out.println("do something....."+str); } } public class MyInvocationHandler implements InvocationHandler { private Object target=null; public MyInvocationHandler(Object _target){ this.target=_target; } @Override public Object invoke(Object target, Method method, Object[] args) throws Throwable { return method.invoke(this.target, args); } } public class DynamicProxy<T> { public static <T> T newProxyInstance(ClassLoader loader,Class<?>[] interfaces,InvocationHandler h){ return (T) Proxy.newProxyInstance(loader,interfaces, h); } } public class Client { public static void main(String[] args) { Subject subject = new RealSubject(); Subject proxy =SubjectDynamicProxy.newProxyInstance(subject);// DynamicProxy.newProxyInstance(sub.getClass().getClassLoader(), sub.getClass().getInterfaces(), h); proxy.dosomeshting("Finish"); } }
被代理的对象需要实现接口
动态代理
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。