cglib中Enhancer的简单使用
cglib 是一個強大的, 高效高質的代碼生成庫.
簡單的使用方法
Enhancer中有幾個常用的方法, setSuperClass和setCallback, 設置好了SuperClass后, 可以使用create制作代理對象了
Enhancer enhancer = new Enhancer();??
enhancer.setSuperclass(EnhancerDemo.class); ?
enhancer.setCallback(new MethodInterceptorImpl());??
EnhancerDemo demo = (EnhancerDemo) enhancer.create();?
實現(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)調用了原來的方法, 在這個調用前后可以添加其他的邏輯, 相當于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;??
? ?? ???}??? ? ? ? ??
? ? }??
}?
運行結果如下:
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首先調用了toString()方法, 然后又調用了hashCode, ?
生成的對象為EnhancerDemo$$EnhancerByCGLIB$$bc9b2066的實例, 這個類是運行時由cglib產(chǎn)生的
轉載于:https://www.cnblogs.com/kristain/articles/2092458.html
總結
以上是生活随笔為你收集整理的cglib中Enhancer的简单使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在GridView中的批量删除!
- 下一篇: BeOS文件系统