jdk动态代理
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
/**
-
@author
-
@date 2022/5/23
-
@Description
*/
public class JDKInvocationTest {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {//cglib代理
// MaoTaiSellImpl target = new MaoTaiSellImpl();
// MaoTaiSellImpl proxyFactory = (MaoTaiSellImpl)new ProxyFactory(target).getProxyInstance();
// int sell = proxyFactory.sell(10);
// System.out.println(“原价-”+10000+" 现价-"+sell);
//jdk代理
MaoTaiSellImpl target = new MaoTaiSellImpl();
InvocationHandler handler = new MySellWineInvocationHandler(target);
SellWine wo = (SellWine)Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), handler);
int price = wo.sell(10);
System.out.println("原价-"+10000+" 现价-"+price);
}
}``
//接口
public interface SellWine {
int sell(int amount);
}
//实现类
public class MaoTaiSellImpl implements SellWine {
@Override
public int sell(int amount) {
int a = amount*1000;
return a;
}
}
//jdk代理实现
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
-
@author
-
@date 2022/5/23
-
@Description
*/
public class MySellWineInvocationHandler implements InvocationHandler {private Object target;
public MySellWineInvocationHandler(Object target){
this.target = target;
}@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object feeObj = method.invoke(target, args);
int feeAmount = (int)feeObj;
int totalFee = feeAmount + (feeAmount/10);
return totalFee;
}
}
//cglib代理
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
/**
-
@author zhoujunfan
-
@date 2022/5/23
-
@Description
*/
public class ProxyFactory implements MethodInterceptor {//目标对象
private Object target;public ProxyFactory(Object target){
this.target=target;
}public Object getProxyInstance(){
Enhancer en = new Enhancer();
en.setSuperclass(target.getClass());
en.setCallback(this);
return en.create();
}
CGLib创建的动态代理对象性能比JDK创建的动态代理对象的性能高不少,但CGLib在创建代理对象时所花费的时间却比JDK多得多,所以对于单例对象,因无需频繁创建对象,用CGLib合适,反之,使用JDK方式要更为合适一些。同时,由于CGLib由于是采用动态创建子类的方法,对于final方法,无法进行代理。
静态代理 参考 实现runable接口开启线程