JDK和cglib的动态代理介绍
MethodInterceptProxy项目
在dexmaker和cglib-for-android库的基础上,修改部分代码后形成我们的类似cglib框架 MethodInterceptProxy ,实现上面需求只需这样写,和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
| final String name = "张五"; Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(PeopleService.class);
MethodInterceptor interceptor = new MethodInterceptor() { @Override public Object intercept(Object object, Object[] args, MethodProxy methodProxy) throws Throwable { Object obj = null; if(name.equals("张三")){ obj = methodProxy.invokeSuper(object, args); ; }else{ System.out.println("----对不起,您没有权限----"); } return obj; } };
enhancer.setCallbacks(new MethodInterceptor[]{interceptor,NoOp.INSTANCE}); enhancer.setCallbackFilter(new CallbackFilter() { @Override public int accept(Method method) { if(method.getName().equals("select")){ return 0; } return 1; } }); PeopleService ps = (PeopleService) enhancer.create(); ps.add();
|
来源:http://blog.csdn.net/zhangke3016/article/details/71437287