理解 newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)三个参数
1:loader:该接口的类加载器或实现该接口的类的加载器
2:interfaces:被代理者的接口
获取方式
2-1,通过代理者的class对象动态获取 RealProxy.class.getInterfaces()
2-2,手动的方式去指定 new Class[]{Interface.class}
22:interfaces:被代理者父类的接口
获取方式
22-1,通过代理者的抽象类class对象动态获取AbstractRealProxy.class.getInterfaces()
22-2,手动的方式去指定 new Class[]{Interface.class}
注意
此时无法通过RealProxy来获取接口信息
System.out.println(Arrays.toString(RealProxy.class.getInterfaces()));
//~output
[]
3:h:是InvocationHandler的一个实例,代理者与被代理者的中间角色;
proxy:其实和Proxy.newProxyInstance产生的代理对象 是一个对象
method:执行的目标方法
args:目标方法的参数
返回的Object是目标方法的返回值
//动态代理者
class DynamicProxy implements InvocationHandler{
//被代理者 我也不知道是谁
private Object object;
DynamicProxy(Object o){this.object = o;}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//该proxy对象 和Proxy.newProxyInstance产生的代理对象 是一个对象
// System.out.println("dynamic-proxy: "+proxy.getClass());
Object res = method.invoke(object, args);
//System.out.println("动态代理,代理者做一些其他事情");
return res;
}
}
探讨:当类关系如图示,没有具体的实现的话,得使用内部类来解决
public interface Humman {
void say();
}
public abstract class Person implements Humman {
@Override
public void say() {
System.out.println("人类用语言进行沟通");
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
class DynamicProxyApp implements InvocationHandler{
//由于method执行的时候 需要一个对象
private Object o;
DynamicProxyApp(Object o){this.o = o;}
DynamicProxyApp(){}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if(o == null){
Method say = Person.class.getDeclaredMethod("say");
//匿名内部类结合接口、抽象类、动态代理的使用
return say.invoke(new Person() {
@Override
public void say() {
//在该位置加上一些特殊得处理
super.say();
}
}, args);
}
System.out.println("执行目标方法前得特殊处理......");
return method.invoke(o,args);
}
}
public class ProxyApp {
public static void main(String[] args) {
proxyApp();
}
public static void proxyApp(){
Humman humman = (Humman) Proxy.newProxyInstance(Humman.class.getClassLoader(),
Person.class.getInterfaces(),new DynamicProxyApp());
humman.say();
}
}