首页 > 代码库 > java的动态代理
java的动态代理
JDK的动态代理public interface Subject { Object request(); void hello();}public class RealSubject implements Subject{ public RealSubject(){}; public Object request() { System.out.println("realsubject"); return 1; } public void hello() { System.out.println("hello"); }}public class ProxySubject implements InvocationHandler { private Object obj; public ProxySubject(Object obj) { this.obj = obj; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("增强前"); //Object m = method.invoke(obj, args); method.invoke(obj, args); System.out.println("增强后"); //return m; return null; }}public class Test { public static void main(String[] args) { ProxySubject proxy = new ProxySubject(new RealSubject()); Subject sub = (Subject) Proxy.newProxyInstance( RealSubject.class.getClassLoader(), RealSubject.class.getInterfaces(), proxy); sub.request(); sub.hello(); }}cglib的动态代理public class HelloWorld { public void sayHelloWorld() { System.out.println("HelloWorld!"); } public int say() { System.out.println(11111111); return 1; }}public class CglibProxy implements MethodInterceptor { private Object obj; public Object createProxy(Object target) { this.obj = target; Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(this.obj.getClass()); enhancer.setCallback(this); enhancer.setClassLoader(target.getClass().getClassLoader()); return enhancer.create(); } public Object intercept(Object proxy, Method method, Object[] params, MethodProxy methodProxy) throws Throwable { System.out.println("增强前"); Object result = methodProxy.invokeSuper(proxy, params); System.out.println("增强后"); return null; }}public class Test { public static void main(String[] args) { HelloWorld hello = new HelloWorld(); CglibProxy cglibProxy = new CglibProxy(); HelloWorld hw=(HelloWorld) cglibProxy.createProxy(hello); hw.sayHelloWorld(); hw.say(); }}
java的动态代理
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。