cglib中Enhancer的简单使用
cglib 是一個強(qiáng)大的, 高效高質(zhì)的代碼生成庫.
簡單的使用方法
Enhancer中有幾個常用的方法, setSuperClass和setCallback, 設(shè)置好了SuperClass后, 可以使用create制作代理對象了
Enhancer enhancer = new Enhancer();??
enhancer.setSuperclass(EnhancerDemo.class); ?
enhancer.setCallback(new MethodInterceptorImpl());??
EnhancerDemo demo = (EnhancerDemo) enhancer.create();?
實(shí)現(xiàn)MethodInterceptor接口
private static class MethodInterceptorImpl implements MethodInterceptor {??
? ?? ???@Override?
? ?? ???public Object intercept(Object obj, Method method, Object[] args,??
? ?? ?? ?? ?? ? MethodProxy proxy) throws Throwable {??
? ?? ?? ?? ?System.out.println("Before invoke " + method);??
? ?? ?? ?? ?Object result = proxy.invokeSuper(obj, args);??
? ?? ?? ?? ?System.out.println("After invoke" + method);??
? ?? ?? ?? ?return result;??
? ?? ???}????
? ? }?
intercept方法, Object result = proxy.invokeSuper(obj, args)調(diào)用了原來的方法, 在這個調(diào)用前后可以添加其他的邏輯, 相當(dāng)于AspectJ的around
完整代碼如下:?
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 EnhancerDemo {??
? ? public static void main(String[] args) {??
? ?? ???Enhancer enhancer = new Enhancer();??
? ?? ???enhancer.setSuperclass(EnhancerDemo.class);??
? ?? ???enhancer.setCallback(new MethodInterceptorImpl());??
? ?? ?? ???
? ?? ???EnhancerDemo demo = (EnhancerDemo) enhancer.create();??
? ?? ???demo.test();??? ? ? ? ?
? ?? ???System.out.println(demo);??
? ? }??
? ? ? ?
? ? public void test() {??
? ?? ???System.out.println("EnhancerDemo test()");??
? ? }??
? ?
? ? private static class MethodInterceptorImpl implements MethodInterceptor {??
? ?? ???@Override?
? ?? ???public Object intercept(Object obj, Method method, Object[] args,??
? ?? ?? ?? ?? ? MethodProxy proxy) throws Throwable {??
? ?? ?? ?? ?System.err.println("Before invoke " + method);??
? ?? ?? ?? ?Object result = proxy.invokeSuper(obj, args);??
? ?? ?? ?? ?System.err.println("After invoke" + method);??
? ?? ?? ?? ?return result;??
? ?? ???}??? ? ? ? ??
? ? }??
}?
運(yùn)行結(jié)果如下:
Before invoke public void EnhancerDemo.test()??
EnhancerDemo test()??
After invokepublic void EnhancerDemo.test()??
Before invoke public java.lang.String java.lang.Object.toString()??
Before invoke public native int java.lang.Object.hashCode()??
After invokepublic native int java.lang.Object.hashCode()??
After invokepublic java.lang.String java.lang.Object.toString()??
EnhancerDemo$$EnhancerByCGLIB$$bc9b2066@1621e42?
我們可以看到System.out.println(demo), demo首先調(diào)用了toString()方法, 然后又調(diào)用了hashCode, ?
生成的對象為EnhancerDemo$$EnhancerByCGLIB$$bc9b2066的實(shí)例, 這個類是運(yùn)行時由cglib產(chǎn)生的
轉(zhuǎn)載于:https://www.cnblogs.com/kristain/articles/2092458.html
總結(jié)
以上是生活随笔為你收集整理的cglib中Enhancer的简单使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在GridView中的批量删除!
- 下一篇: BeOS文件系统