作用就是通过提供一个代理类,让我们在调用目标方法的时候,不再是直接对目标方法进行调用,而是通过代理类间接调用。让不属于目标方法核心逻辑的代码从目标方法中剥离出来——解耦。调用目标方法时先调用代理对象的方法,减少对目标方法的调用和打扰,同时让附加功能能够集中在一起也有利于统一维护。
例如:我在4s店买车,4s店帮车工厂卖车给我
实现:1.newProxyInstance():创建一个代理实例,其中有三个参数:
classLoader:加载动态生成的代理类的类加载器
interfaces:目标对象实现的所有接口的class对象所组成的数组
invocationHandler:设置代理对象实现目标对象方法的过程,即代理类中如何重写接口中的抽象方法
2.invocationHandler中的方法invoke,三个参数:
proxy:代理对象
method:代理对象需要实现的方法,即其中需要重写的方法
args:method所对应方法的参数
public Object getProxy(){
ClassLoader classLoader = target.getClass().getClassLoader();
Class<?>[] interfaces = target.getClass().getInterfaces();
InvocationHandler invocationHandler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
try {
result = method.invoke(target, args);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
};
return Proxy.newProxyInstance(classLoader, interfaces, invocationHandler);
}
}