public interface SaleComputer {
public String sale(int money);
public void show();
}
public class Lenovo implements SaleComputer{
@Override
public String sale(int money) {
System.out.println("花费了"+money+"购买电脑联想!");
return "联想电脑";
}
@Override
public void show() {
System.out.println("我买的是联想电脑");
}
}
package proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyTest {
public static void main(String[] args) {
//创建真实对象
Lenovo le=new Lenovo();
//动态代理增强对象
/*
三个参数:
1.类加载器:真实对象 Lenovo.class.getClassLoader()
2.接口数组:真实对象 Lenovo.class.getInterfaces()
3.处理器:new InvocationHandler()
*/
SaleComputer proxy = (SaleComputer) Proxy.newProxyInstance(Lenovo.class.getClassLoader(), Lenovo.class.getInterfaces(), new InvocationHandler() {
@Override
/*
参数:
1.proxy:代理对象
2.method:代理对象调用的方法,被封装为的对象
3.args:代理对象调用的方法时,传递的实际参数
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// System.out.println("该方法被执行了!");
// System.out.println(method.getName());//sale
// System.out.println(args[0]);//8000
if(method.getName().equals("sale")){
System.out.println("免费接你。。。");
String co = (String) method.invoke(le, args);//强制转换是为了返回值那
System.out.println("免费送货。。。。");
return co+"_鼠标";
}else {
Object co = method.invoke(le, args);
return co;
}
}
});
String sale = proxy.sale(8000);
System.out.println(sale);
//免费接你。。。
//花费了8000购买电脑联想!
//免费送货。。。。
//联想电脑_鼠标
}
}
idea实现JDK动态代理
最新推荐文章于 2022-11-08 05:12:32 发布