静态代理
代理类和被代理类 实现同一个接口
缺点就是一个代理类只能针对一个接口
public interface Sale {
public int saleGoods();
}
public class Factory implements Sale {
@Override
public int saleGoods() {
System.out.println("2块钱,你买不了吃亏");
return 2;
}
}
public class Store implements Sale {
private Factory f;
public Store(Factory f) {
this.f = f;
}
@Override
public int saleGoods() {
int price = f.saleGoods();
System.out.println("10快钱,你买不了上当");
return price + 8;
}
}
public class Test {
public static void main(String[] args) {
Factory f = new Factory();
Store s = new Store(f);
s.saleGoods();
}
}
动态代理
动态代理分为两种
jdk and
cglib
jdk
jdk 代理主要用到了
接口InvocationHandler 此接口只有一个方法(代码如下)
InvocationHandler的实现类可以理解成具体的代理实现
类Proxy
生成代理的具体的操作类,可以为一个or多个接口动态的实现代理类
缺点 就是被代理的类必须是接口的实现类(依赖于接口),
如果某些类没有实现接口 则不能用jdk代理
public interface Sale {
public int saleGoods();
}
public class Factory implements Sale {
int price;
@Override
public int saleGoods() {
System.out.println("2块钱,买不了吃亏");
price = 2;
return price;
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyStore implements InvocationHandler {
Object factory;
public Object bind(Object factory) {
this.factory = factory;
return Proxy.newProxyInstance(factory.getClass().getClassLoader(),
factory.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("before proxy");
Object result = method.invoke(factory, args);
System.out.println("after proxy");
return result;
}
}
public class Test {
public static void main(String[] args) {
Factory f = new Factory();
Store s = new Store(f);
s.saleGoods();
}
}
cglib
原理是针对target类 生成一个子类 覆盖方法实现增强
缺点 基于继承 无法代理final类(final类无法被继承,如String)
需要的jar包 :asm-3.3.1,cglib-2.2.jar ps:jar包版本不同可能会报错
public class Factory {
int price;
public int saleGoods(int price) {
System.out.println(price + "块钱,买不了吃亏");
this.price = price = 2;
return price;
}
}
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 ProxyStoreCgLib implements MethodInterceptor {
Object target;
public Object getInstanceByMe(Object target) {
this.target = target;
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(target.getClass());
enhancer.setCallback(this);
return enhancer.create();
}
@Override
public Object intercept(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable {
System.out.println("before");
proxy.invokeSuper(obj, args);
System.out.println("after");
return null;
}
}
public class TestPorxy {
public static void main(String[] args) {
Factory factory = new Factory();
ProxyStoreCgLib proxyCg = new ProxyStoreCgLib();
Factory factoryProxy = (Factory) proxyCg.getInstanceByMe(factory);
factoryProxy.saleGoods(10);
}
}