簡述:
試用cglib做字節碼加強
參考:
http://www.cnblogs.com/kristain/articles/2092458.html
EnhancerTest.java
package com.anialy.test.jvm.outofmemeoryerror;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
/**
* Cglib進行對類的字節碼增強
*/
public class EnhancerTest {
public String process(){
return "process finished";
}
public static void main(String[] args) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(EnhancerTest.class);
enhancer.setUseCache(false);
enhancer.setCallback(new MethodInterceptor() {
public Object intercept(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable {
System.out.printf("do somthing before method-%s \n", method.getName());
Object result = proxy.invokeSuper(obj, args);
System.out.printf("do somthing after method-%s \n", method.getName());
return result;
}
});
// construct Test object
EnhancerTest test = (EnhancerTest) enhancer.create();
System.out.printf("result: %s\n", test.process());
}
}
輸出: