java cglib

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

 

你可能感兴趣的:(java)