Cglib 字節碼加強試用

簡述:

試用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());
	}
}




輸出:










發佈了225 篇原創文章 · 獲贊 34 · 訪問量 222萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章