java cglib

1531 ワード

1.pomファイル
        
			cglib
			cglib
			3.2.10
		

2.テストクラスA
package com.knife.testcglib;

public class A {
	
	public void test(){
		System.out.println("test ...");
	}
	
	public int add(int i){
		return i++;
	}
}

3.MethodInterceptorを実装するクラス
package com.knife.testcglib;

import java.lang.reflect.Method;

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class MyInterceptor implements MethodInterceptor {

	public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3) throws Throwable {
		// TODO Auto-generated method stub
		
		System.out.println(arg1.getName()+" be called ");
		
		if(arg2!=null){
			System.out.println("params:");
			for(Object o:arg2)
				System.out.println(o.toString());
		}
		
		if(arg1.getName().equals("add"))
			return 100;
		else
			return null;
	}

}

4.テスト
package com.knife.testcglib;

import net.sf.cglib.proxy.Enhancer;

public class testCglib {

	public static void main(String args[]){
		MyInterceptor mi=new MyInterceptor();
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(A.class);
		enhancer.setCallback(mi);
		A a=(A)enhancer.create();
		a.test();
		System.out.println(a.add(1));
	}
	
}

5.結果
test be called 
params:
add be called 
params:
1
100