JDK动态代理

理解

代理类生成,只要有接口就可以,不需要实现类。

创建接口

1 package com.jtfr;
2 public interface MyInterface {
3     void say();
4 }

创建实现类

1 package com.jtfr;
2 public class MyClass implements MyInterface {
3     public void say() {
4         System.out.println("被代理类");
5     }
6 }

创建InvocationHandler的实现类

 1 package com.jtfr;
 2 import java.lang.reflect.InvocationHandler;
 3 import java.lang.reflect.Method;
 4 import java.lang.reflect.Proxy;
 5 public class MyInvocationHandler implements InvocationHandler{
 6     private static MyInvocationHandler myInvocationHandlerInstance = new MyInvocationHandler();
 7     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
 8         System.out.println("进入了代理类");
 9         return null;
10     }
11 //    public static <T> T getProxyInstance(Class<T> cls) {
12 //        return (T)Proxy.newProxyInstance(MyInvocationHandler.class.getClassLoader(), cls.getInterfaces(), myInvocationHandlerInstance);
13 //    }
14     // 充分说明了,代理类不需要实现类也可以。
15     public static <T> T getProxyInstance(Class<T> cls) {
16         return (T)Proxy.newProxyInstance(MyInvocationHandler.class.getClassLoader(), new Class[]{cls}, myInvocationHandlerInstance);
17     }
18 }

测试类

1 package com.jtfr;
2 public class ProxyMain {
3     public static void main(String[] args) {
4         //MyInterface MyInterface = MyInvocationHandler.getProxyInstance(MyClass.class);
5         // 这种方式充分说明了,不需要事先类也可以。
6         MyInterface MyInterface = MyInvocationHandler.getProxyInstance(MyInterface.class);
7         MyInterface.say();// 这里执行,说明进入了代理类, 也就说明了不需要实现类也可以的。
8     }
9 }

 输出结果

 

posted @ 2019-06-05 22:26  钧天府人  阅读(234)  评论(0)    收藏  举报