![]()
package com.example;
/**
* 消费者
*/
public class Client {
public static void main(String[] args) {
IProducer producer = Proxy2.getProducer(Producer.class);
producer.saleProduct(10000f);
}
}
package com.example;
/**
* 生产厂家标准
*/
public interface IProducer {
/**
* 销售
* @param money
*/
public void saleProduct(float money);
/**
* 销后
* @param money
*/
public void afterService(float money);
}
package com.example;
/**
* 生产者
*/
public class Producer implements IProducer {
/**
* 销售
* @param money
*/
public void saleProduct(float money){
System.out.println("销售产品,并拿到钱:"+money);
}
/**
* 销后
* @param money
*/
public void afterService(float money){
System.out.println("销后服务,并拿到钱:"+money);
}
}
package com.example;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class Proxy2 {
public static <T> T getProducer(Class<T> tClass){
//ClassLoader:被代理对象的类加载器
//Class[]:被代理对象的接口
//InvocationHandler:增强代码
T proxy = null;
try {
proxy = (T) Proxy.newProxyInstance(tClass.getClassLoader(), tClass.getInterfaces(), new InvocationHandler() {
T t=(T)Class.forName(tClass.getName()).newInstance();
/**
*
* @param proxy
* @param method
* @param args
* @return
* @throws Throwable
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if("saleProduct".equals(method.getName())){
args[0]=0.8f*(float)args[0];
}
return method.invoke(t,args);
}
});
} catch (Exception e) {
e.printStackTrace();
}
return proxy;
}
}