JDK动态代理必须实现接口,通过反射来动态代理方法,缺点是消耗系统性能。但是无需产生过多的代理类,避免了重复代码的产生,系统更加灵活。可以看到JDK动态代理比静态代理更加灵活。
public class JDKTest {
public static void main(String[] args) {
Factory factory = new Factory();
InvocationHandler invocationHandler = new Taobao(factory);
Usb o = (Usb) Proxy.newProxyInstance(factory.getClass().getClassLoader(),
factory.getClass().getInterfaces(), invocationHandler);
int sell = o.sell();
System.out.println(sell);
}
}
//目标接口
interface Usb {
int sell();
}
//目标类
class Factory implements Usb {
@Override
public int sell() {
return 10;
}
}
//动态代理类
class Taobao implements InvocationHandler {
private Object target;
public Taobao() {
}
public Taobao(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object ret = method.invoke(target, args);
int price = (int) ret;
return price + 10;
}
}
网友评论