直接上代码
接口:
package cglibProxy;
public interface Magic {
public void attack();
}
实现类:
package cglibProxy;
/**
* 没有实现接口
*/
public class MagicImpl {
public void attack() {
// TODO Auto-generated method stub
System.out.println("MacigImpl->attack");
}
}
代理类:
package cglibProxy;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
/**
* Cglib动态代理的基础是建立一个目标类的子类,然后调用父类的方法,所以不能代理final修饰的类
*
*/
public class MagicCglib implements MethodInterceptor{
// private Object target;
/**
* 创建代理对象
* @param obj
* @return
*/
public Object createMagic(Object obj){
// this.target=obj;
Enhancer enhancer=new Enhancer();
enhancer.setSuperclass(obj.getClass());
enhancer.setCallback(this);
Object result=enhancer.create();
return result;
}
@Override
public Object intercept(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable {
// TODO Auto-generated method stub
System.out.println("方法调用开始------------");
Object result=proxy.invokeSuper(obj, args);
System.out.println("方法调用结束------------");
return result;
}
}
测试类:
package cglibProxy;
/**
* 用到的jar包:cglib-3.1.jar,asm-4.2.jar
*
* 在cglib-3.1.jar的DebuggingClassWriter类继承了ClassVisitor
* asm-3.2.jar的ClassVisitor是一个interface,使用时会报错,4.2版本的ClassVisitor是class不会报错
*
*/
public class TestCglib {
public static void main(String[] args) {
MagicCglib magicCglib=new MagicCglib();
MagicImpl magic=(MagicImpl)magicCglib.createMagic(new MagicImpl());
magic.attack();
}
}