设计模式之动态代理(2)

package com.ietree.basicskill.designpattern.dynamicproxy.cglib; /** * 实现类 * * @author Root */ public class SomeService { public String doFirst() { System.out.println("执行doFirst()..."); String result = "abcde"; return result; } public void doSecond() { System.out.println("执行doSecond()..."); } }

代理类MyCglibFactory:

package com.ietree.basicskill.designpattern.dynamicproxy.cglib; import java.lang.reflect.Method; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; public class MyCglibFactory implements MethodInterceptor { private SomeService target; public MyCglibFactory() { super(); target = new SomeService(); } public SomeService myCglibCreator() { // 创建增强器对象 Enhancer enhancer = new Enhancer(); // 指定目标类,即父类 enhancer.setSuperclass(SomeService.class); // 设置回调接口对象 enhancer.setCallback(this); return (SomeService) enhancer.create(); } @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { // 调用目标方法 Object result = method.invoke(target, args); if (result != null) { result = ((String) result).toUpperCase(); } return result; } }

测试:

package com.ietree.basicskill.designpattern.dynamicproxy.cglib; public class Main { public static void main(String[] args) { SomeService service = new MyCglibFactory().myCglibCreator(); String result = service.doFirst(); System.out.println("result = " + result); service.doSecond(); } }

运行结果:

执行doFirst()... result = ABCDE 执行doSecond()...

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/3bb66647e8dcfd46a40d18c11fced8c6.html