欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

java动态代理与cglib动态代理

时间:2023-07-06

java动态代理与cglib动态代理

public interface Subject { String sayHelloWorld(String name,Subject subject); Subject sayBye(); void haha();}

public class RealSubject implements Subject{ private String stest; public String getStest() { return stest; } public void setStest(String stest) { this.stest = stest; } @Override @NotNull public String sayHelloWorld(String name,Subject subject) { return "hello"+name; } @Override public Subject sayBye() { RealSubject subject= new RealSubject(); subject.setStest("good job!"); System.out.println("good Job!"); return subject; } public void haha(){ System.out.println("测试************"); }}

public class ProxyMain { public static void main(String[] args) { Subject subject = (Subject) jdkProxy(); subject.sayBye(); Subject subject1 = (Subject) cglibProxy(); subject1.sayBye(); } public static Object jdkProxy() { Subject subject = new RealSubject(); Class[] interfaces = subject.getClass().getInterfaces(); return Proxy.newProxyInstance(subject.getClass().getClassLoader(), interfaces, (proxy, method, args) -> { System.out.println("调用之前"); System.out.println(method.getName()); switch (method.getName()) { case "SayHelloWorld": return "" + method.invoke(subject, args); case "sayBye": Object object = method.invoke(subject, args); return object; case "haha": return null; default: return new Object(); } }); } public static Object cglibProxy() { Subject subject = new RealSubject(); Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(subject.getClass()); MethodInterceptor methodInterceptor = (proxy, method, obj, methodProxy) -> { System.out.println("调用之前"); System.out.println("Method" + method); switch (method.getName()) { case "sayHelloWorld": String string = (String) methodProxy.invoke(subject, obj); return "" + string; case "sayBye": Object object = methodProxy.invoke(subject, obj); return object; case "haha": return null; default: return new Object(); } }; enhancer.setCallback(methodInterceptor); return enhancer.create(); }}

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。