package com.ruoyi.estate.third.aspect;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @Description:
* @Author: lvjie
* @Date: 2022/5/10 10:13
*/
public class ProxyTest {
public static void main(String[] args) {
// 创建被代理的实例对象
Person renter = new Renter();
// 创建InvocationHandler对象
InvocationHandler renterHandler = new RenterInvocationHandler<>(renter);
// 创建代理对象,代理对象的每个执行方法都会替换执行Invocation中的invoke方法
Person renterProxy = (Person) Proxy.newProxyInstance(Person.class.getClassLoader(),new Class<?>[]{Person.class}, renterHandler);
// RenterInvocationHandler 中只有一个invoke函数,这里可以代理不同的多个方法
renterProxy.rentHouse();
renterProxy.saleHouse();
//也可以使用下面的方式创建代理类对象,Proxy.newProxyInstance其实就是对下面代码的封装
/*try {
//使用Proxy类的getProxyClass静态方法生成一个动态代理类renterProxy
Class<?> renterProxyClass = Proxy.getProxyClass(Person.class.getClassLoader(), new Class<?>[]{Person.class});
//获取代理类renterProxy的构造器,参数为InvocationHandler
Constructor<?> constructor = renterProxyClass.getConstructor(InvocationHandler.class);
//使用构造器创建一个代理类实例对象
Person renterProxy = (Person)constructor.newInstance(renterHandler);
renterProxy.rentHouse();
renterProxy.saleHouse();
//
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
}
interface Person {
//租房
void rentHouse();
//卖房
void saleHouse();
}
class Renter implements Person{
@Override
public void rentHouse() {
System.out.println("客人租房成功!");
}
@Override
public void saleHouse() {
System.out.println("客人买房成功!");
}
}
class RenterInvocationHandler<T> implements InvocationHandler {
//被代理类的对象
private T target;
public RenterInvocationHandler(T target){
this.target = target;
}
/**
* proxy:代表动态代理对象
* method:代表正在执行的方法
* args:代表调用目标方法时传入的实参
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
//代理过程中插入其他操作
System.out.println("客人和中介交流");
Object result = method.invoke(target, args);
return result;
}
}
代码修改前摘自 https://blog.csdn.net/qq_34609889/article/details/85317582