CGlib动态代理CallbackFilter

1、Car.java

package com.ast.cglib.test;

public class Car {

}

2、Truck.java

package com.ast.cglib.test;

public class Truck extends Car{

}

3、MyInterceptor.java

package com.ast.cglib.test;

import java.lang.reflect.Method;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class MyInterceptor implements MethodInterceptor{

	@Override
	public Object intercept(Object invoker, Method method, Object[] args,
			MethodProxy proxy) throws Throwable {
		
		System.out.println("NewCarInterceptor intercept before invoke");
		
		Object result = proxy.invokeSuper(invoker, args);
		
		System.out.println("NewCarInterceptor intercept after invoke");
		
		return result;
	}

}

4、MyCallbackFilter.java

package com.ast.cglib.test;

import java.lang.reflect.Method;

import net.sf.cglib.proxy.CallbackFilter;

public class MyCallbackFilter implements CallbackFilter {
	
	public int accept(Method method) {
		if (method.getName().equals("NewTruck")) {
			return 0;
		} else {
			return 1;
		}
	}
}

5、CarFactory.java

package com.ast.cglib.test;

import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.NoOp;

public class CarFactory{
	public Car NewCar()
	{
		System.out.println("CarFactory NewCar");
		return new Car();
	}
	
	public Truck NewTruck()
	{
		System.out.println("CarFactory NewTruck");
		return new Truck();
	}
	
	public static void EnhancerTest()
	{
		Callback[] callbacks = new Callback[] {new MyInterceptor(),  NoOp.INSTANCE};
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(CarFactory.class);
		enhancer.setCallbacks(callbacks);
		enhancer.setCallbackFilter(new MyCallbackFilter());
		
		CarFactory fac = (CarFactory)enhancer.create();
		//NoOp
		fac.NewCar();
		//MyInterceptor
		fac.NewTruck();
	}
	
	public static void main(String[] args)
	{
		CarFactory.EnhancerTest();
	}
}

Comments are closed.