理解 newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)三个参数

    1:loader:该接口的类加载器或实现该接口的类的加载器
    image.png
    2:interfaces:被代理者的接口
    获取方式
    2-1,通过代理者的class对象动态获取 RealProxy.class.getInterfaces()
    2-2,手动的方式去指定 new Class[]{Interface.class}

    image.png
    22:interfaces:被代理者父类的接口
    获取方式
    22-1,通过代理者的抽象类class对象动态获取AbstractRealProxy.class.getInterfaces()
    22-2,手动的方式去指定 new Class[]{Interface.class}
    注意
    此时无法通过RealProxy来获取接口信息

    1. System.out.println(Arrays.toString(RealProxy.class.getInterfaces()));
    2. //~output
    3. []

    3:h:是InvocationHandler的一个实例,代理者与被代理者的中间角色;
    proxy:其实和Proxy.newProxyInstance产生的代理对象 是一个对象
    method:执行的目标方法
    args:目标方法的参数
    返回的Object是目标方法的返回值

    1. //动态代理者
    2. class DynamicProxy implements InvocationHandler{
    3. //被代理者 我也不知道是谁
    4. private Object object;
    5. DynamicProxy(Object o){this.object = o;}
    6. @Override
    7. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    8. //该proxy对象 和Proxy.newProxyInstance产生的代理对象 是一个对象
    9. // System.out.println("dynamic-proxy: "+proxy.getClass());
    10. Object res = method.invoke(object, args);
    11. //System.out.println("动态代理,代理者做一些其他事情");
    12. return res;
    13. }
    14. }

    探讨:当类关系如图示,没有具体的实现的话,得使用内部类来解决
    image.png

    1. public interface Humman {
    2. void say();
    3. }
    4. public abstract class Person implements Humman {
    5. @Override
    6. public void say() {
    7. System.out.println("人类用语言进行沟通");
    8. }
    9. }
    10. import java.lang.reflect.InvocationHandler;
    11. import java.lang.reflect.Method;
    12. import java.lang.reflect.Proxy;
    13. class DynamicProxyApp implements InvocationHandler{
    14. //由于method执行的时候 需要一个对象
    15. private Object o;
    16. DynamicProxyApp(Object o){this.o = o;}
    17. DynamicProxyApp(){}
    18. @Override
    19. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    20. if(o == null){
    21. Method say = Person.class.getDeclaredMethod("say");
    22. //匿名内部类结合接口、抽象类、动态代理的使用
    23. return say.invoke(new Person() {
    24. @Override
    25. public void say() {
    26. //在该位置加上一些特殊得处理
    27. super.say();
    28. }
    29. }, args);
    30. }
    31. System.out.println("执行目标方法前得特殊处理......");
    32. return method.invoke(o,args);
    33. }
    34. }
    35. public class ProxyApp {
    36. public static void main(String[] args) {
    37. proxyApp();
    38. }
    39. public static void proxyApp(){
    40. Humman humman = (Humman) Proxy.newProxyInstance(Humman.class.getClassLoader(),
    41. Person.class.getInterfaces(),new DynamicProxyApp());
    42. humman.say();
    43. }
    44. }