接口类
public interface Runway {
void catwalk();
void pose();
}
接口实现类
public class Model implements Runway{
private String name;
public Model(String name) {
this.name = name;
}
@Override
public void catwalk() {
System.out.println(name+" catwalks so graceful.");
}
@Override
public void pose() {
System.out.println(name+" posed very charmingly.");
}
}
代理创建类
public class ProxyModelHome {
/**
* 创建一个方法,返回一个模特代理对象
* 这个方法的返回值是Runway接口,所以将是其实现类的代理
* 接的参数就是一个模特对象
*/
public static Runway getProxy(Model m){
/**
* return Proxy.newProxyInstance的返回值是Object,所以要类型转换
* 三个参数的意思
* 一.get该类加载器,生成代理对象
* the class loader that loaded the class or interface represented by this Class object.
* 二.get该类继承的接口数组,通过接口,将需要被代理的方法交给代理对象
* Returns the interfaces directly implemented by the class or interface represented by this Class object.
* 三.new一个方法调用 handler,代理的核心处理程序
*/
return (Runway) Proxy.newProxyInstance(m.getClass().getClassLoader(),
m.getClass().getInterfaces(),
new InvocationHandler() {//第一次写,不用lambda表达式
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Arrange Runway Show");
Object rs = method.invoke(m,args);
System.out.println("Arrange Model's exit");
return rs;
//这个返回值的作用没搞明白,总之返回值为method.invoke不会报NPE
}
});
}
}
测试执行体
public class TestDemo {
public static void main(String[] args) {
Model md = new Model("Monica");
Runway rw1 = ProxyModelHome.getProxy(md);
rw1.catwalk();
rw1.pose();
}
}
本文详细介绍了如何在Java中创建动态代理,包括定义接口、实现接口的类、动态代理生成类以及测试执行过程,深入解析了Java动态代理的使用方法。
2459

被折叠的 条评论
为什么被折叠?



