JAVA全系列 教程
3762个小节阅读:7088.4k
目录
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
JDK动态代理是针对接口进行代理,所以我们要写被代理的接口和该接口的实现类。
x// 被代理接口
public interface Apple {
String sell(double price);//卖产品
void repair();// 维修
}
// 被代理接口的实现类
public class AppleImpl implements Apple{
@Override
public String sell(double price) {
System.out.println("产品卖了"+price+"元");
return "iphone13";
}
@Override
public void repair() {
System.out.println("苹果售后维修");
}
}
// 代理方式类,定义被代理方法的增强方式
// 该类实现InvocationHandler接口,重写invoke方法,定义方法的增强方式
public class ShoppingProxy implements InvocationHandler {
private Apple apple;// 被代理对象
public ShoppingProxy(Apple apple) {
this.apple = apple;
}
/**
* 定义原方法的增强方式
* @param proxy 被代理对象
* @param method 被代理对象调用的方法
* @param args 被代理对象调用的方法时,传入的参数
* @return 方法的返回值
* @throws Throwable
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String name = method.getName(); //被代理对象执行的方法名
if("sell".equals(name)){
double price = (double)args[0]*0.9; //增强参数
Object result = method.invoke(apple, price); // 执行方法
return result + "和充电头"; // 增强返回值
}else if("repair".equals(name)){
System.out.println("专属客服为您服务!"); // 增强方法流程
return method.invoke(apple,args);
}else{
return method.invoke(apple,args); // 什么都不增强
}
}
}
public class Test {
public static void main(String[] args) {
// 被代理对象
Apple apple = new AppleImpl();
// 代理方式对象
ShoppingProxy shoppingProxy = new ShoppingProxy(apple);
// 生成代理对象
Apple appleJD = (Apple) Proxy.newProxyInstance(
apple.getClass().getClassLoader(), // 类加载器
apple.getClass().getInterfaces(),//被代理接口
shoppingProxy //代理方式对象
);
// 执行增强后的方法
String sell = appleJD.sell(6000);
System.out.println(sell);
appleJD.repair();
}
}
1. 关于JDK实现动态代理,说法不正确的是?
A 是针对接口进行代理。
B 是针对类进行代理。
C 要写被代理的接口和该接口的实现类。
D 不会生成代理类,只会生成代理对象。
1=>B