JDK官方的Proxy类创建代理对象
基于接口的动态代理
提供者:JDK官方的Proxy类。
要求:被代理类最少实现一个接口。
public class Producer implements ImProducer {
public void saleProduct(Float money) {
System.out.println("销售商品,金额是:"+money);
}
public void afterService(Float money) {
System.out.println("提供售后服务,金额是:"+money);
}
}
创建JDK动态代理
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class din{
public static void main(String[] args) {
Producer producer2 = new Producer();
producer2.saleProduct(500f);
producer2.afterService(100f);
ImProducer imProducer = (ImProducer) Proxy.newProxyInstance(
producer2.class.getClassLoader(),
producer2.class.getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Float money = (Float) args[0];
String name = method.getName();
Object result = null;
if(name.equals("saleProduct")){
result= method.invoke(producer2,money*0.75f);
}else if(name.equals("saleProduct")){
result= method.invoke(producer2,money*0.9f);
}
return result;
}
}
);
proxyProducer.saleProduct(100f);
proxyProducer.afterService(100f);
}
}