清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>
cglib实现动态代理构建带参数的代理实例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; import java.lang.reflect.Method; /** * Created by Carl on 14-12-30. */ public class CglibProxy implements MethodInterceptor{ /** * 创建代理对象方法 * * @param target 代理对象 * @param args 对应的构造器参数类型 * * 例:有构造器如下 * public Person(name,age){...} name为String.class age为int.class * 写入name的类型与age的类型 * * 则:new Class[]{String.class,int.class} * * @param argsValue 对应的构造器参数值 * * 例:如此创建对象 new Person("name",23) 用以下方式传入:new Object[]{"name",23} * * @param <T> <泛型方法> * @return 返回跟代理对象类型 */ public <T> T getInstance(T target,Class[] args,Object[] argsValue){ Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(target.getClass()); enhancer.setCallback( this ); return (T) enhancer.create(args,argsValue); } /** * 创建代理对象方法 * * @param target 代理对象 * @param <T> <泛型方法> * @return 返回跟代理对象类型 */ public <T> T getInstance(T target){ Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(target.getClass()); enhancer.setCallback( this ); return (T) enhancer.create(); } @Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { Object result = null ; try { System.out.println( "Before " +method.getName()+ " .." ); result = methodProxy.invokeSuper(o,objects); System.out.println( "End " +method.getName()+ " .." ); } catch (Exception e){ System.out.println( "Errod " +method.getName()+ " .." ); } return result; } } |
需引入 cglib-2.1.3.jar 和 asm.jar