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()...