标签:int tor 定义 不同 image super 调用 override 接口
java动态代理的定义:为其他目标类的方法增加切面的逻辑,即在执行目标类方法的时候,先去执行一段如校验检测的逻辑代码。java通俗一点就是生成一个继承目标类的子类,并在每个调用方法都添加一段逻辑。
package cglib;
public class Star implements Speak,Eat{
@Override
public void say() {
// TODO Auto-generated method stub
System.out.println("i am a star");
}
@Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("star eats some fruit");
}
}
package cglib;
//装饰器模式
public class Broker implements Speak{
private Speak speak;
public Broker(Speak speak){
this.speak=speak;
}
@Override
public void say() {
// TODO Auto-generated method stub
speak.say();
}
}
package cglib;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class JDKDynamicProxy implements InvocationHandler{
private Object speak;
private JDKDynamicProxy(Object speak){
//传入star对象
this.speak=speak;
}
//创建一个静态方法,生成代理类,
public static Object newProxyInstance(Object speak){
System.out.println(JDKDynamicProxy.class.getClassLoader().toString());
return Proxy.newProxyInstance(JDKDynamicProxy.class.getClassLoader(),new Class[]{Speak.class,Eat.class}, new JDKDynamicProxy(speak));
}
//覆盖InvocationHandler的invoke方法,从参数可以看出,这个方法明显使用了jdk的方法映射来调用Star的方法,在调用Star的方法前后,我们都可以增加自己的逻辑代码
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
System.out.println("call the JDKDynamicProxy");
return method.invoke(speak, args);
}
}
package cglib;
import java.lang.reflect.Constructor;
public class ProxyTest {
public static void main(String[] args) {
//装饰者模式
Star star=new Star();
Speak b=new Broker(star);
b.say();
//jdk动态代理模式
Speak s=(Speak) JDKDynamicProxy.newProxyInstance(star);
s.say();
Eat e=(Eat) JDKDynamicProxy.newProxyInstance(star);
e.eat();
//CGlib动态代理
Speak sp=CGProxy.newCGproxyInstance(Star.class);
sp.say();
}
}
package cglib;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
public class CGProxy implements MethodInterceptor {
public static <T extends Speak> Speak newCGproxyInstance(Class<T> superClass){
Enhancer en=new Enhancer();
en.setSuperclass(superClass);
en.setCallback(new CGProxy());
return (Speak)en.create();
}
@Override
public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3) throws Throwable {
// TODO Auto-generated method stub
System.out.println("call the CGProxy");
return arg3.invokeSuper(arg0, arg2);
}
}
标签:int tor 定义 不同 image super 调用 override 接口
原文地址:http://www.cnblogs.com/zhenyimo/p/6837321.html