美文网首页Java基础
java 反射 注解 代理

java 反射 注解 代理

作者: pj0579 | 来源:发表于2019-10-10 17:11 被阅读0次

    注解的使用通常配合反射使用
    动态代理需要反射机制配合
    简单说下注解:
    注解是元数据:数据的数据,可以给方法 类 变量增加额外的数据。
    一个简单的注解形式:

    @Documented // 作用编写文档
    @Target(ElementType.METHOD) // 默认都可以修饰 修饰方法
    @Inherited // 具有继承性 子类自动备注修饰
    @Retention(RetentionPolicy.RUNTIME) // 注解保留的时间 有SOURCE CLASS RUNTIME 分别对应 编译后丢弃 运行时不保留 运行时可以通过反射获取
    public @interface CustomAnnotaton {
        String name();
        String test() default "w";
    }
    

    可以通过反射获取方法上注解的值

    // 利用反射获取注解
            Class Test = AnnotationFiled.class;
            Method[] methods = Test.getMethods();
            for (Method method : methods) {
                if (method.isAnnotationPresent(CustomAnnotaton.class)) {
                    CustomAnnotaton annotationInfo = method.getAnnotation(CustomAnnotaton.class);
                    System.out.println("method: "+ method);
                    System.out.println("name= "+ annotationInfo.name() +
                            " ,test= "+ annotationInfo.test()
                           );
                }
            }
    

    获取注解的时候用到了反射
    反射:使程序可以动态的使用对象的功能。

    功能:
    1.在运行时判断任意一个对象所属的类。
    2.在运行时构造任意一个类的对象。
    3.在运行时判断任意一个类所具有的成员变量和方法。
    4.在运行时调用任意一个对象的方法。
    5.生成动态代理。

    使用:

    // 获取类对象
    Class A = Class.forName("xxx");
    Class B = xxx.class;
    Class C = xxx.getClass();
    // 获取方法
    Method[] methods = A.getMethods();  // 公共方法
    // 获取变量
    Field[] publicFields = class1.getFields(); //获取class对象的public属性
    // 获取注解 
    Annotation[] annotations = (Annotation[]) class1.getAnnotations();//获取class对象的所有注解
    ...还有许多方法不一一列举
    

    动态代理怎么配合反射使用?
    静态代理
    不需要通过反射实现,在编译时已经实现。

    // 代理类 真实类需要实现接口
    interfece Print{
    public void print();
    }
    // 真实类
    class RealObject implements Print{
    public void print() {
    System.out.print("realObject");
       }
    }
    // 代理类
    class Proxy  implements Print{
          private Print print;
          public Proxy(Print print){
            this.print = print;
         }
          public void print() {
            print.print();
           }
    }
    

    而动态代理需要反射实现
    运行时动态生成代理类

    public class DynamicProxy {
        public static void main(String[] args) {
            //1.创建目标对象
            RealObejct realSubject = new RealObejct();
            //2.创建调用处理器对象
            ProxyHandler handler = new ProxyHandler(realSubject);
            //3.动态生成代理对象
            TestObject proxySubject = (TestObject) Proxy.newProxyInstance(RealObejct.class.getClassLoader(),
                    RealObejct.class.getInterfaces(), handler);
            //4.通过代理对象调用方法 这个时候会走到ProxyHandler的invoke方法
            proxySubject.print();
        }
    }
    
    interface TestObject{
        public void print();
    }
    
    class RealObejct implements TestObject{
    
        @Override
        public void print() {
            System.out.printf("RealObject");
        }
    }
    
    /**
     * 代理类的调用处理器
     */
    class ProxyHandler implements InvocationHandler {
        private TestObject subject;
    
        public ProxyHandler(TestObject subject) {
            this.subject = subject;
        }
    
        @Override
        public Object invoke(Object proxy, Method method, Object[] args)
                throws Throwable {
            //定义预处理的工作,当然你也可以根据 method 的不同进行不同的预处理工作
            System.out.println("====before====");
            //调用RealSubject中的方法
            Object result = method.invoke(subject, args);
            System.out.println("====after====");
            return result;
        }
    }
    

    来看下Proxy.newProxyInstance怎么实现的

    public static Object newProxyInstance(ClassLoader loader,
                                              Class<?>[] interfaces,
                                              InvocationHandler h)
            throws IllegalArgumentException
        {
            // 检查 h 是否为null 抛出异常
            Objects.requireNonNull(h);
            // 接口类c复制一份
            final Class<?>[] intfs = interfaces.clone();
            // 获取代理类对象 会创建一个代理类字节码文件然后加载到虚拟机 对应真实类的方法 里面会有InvocationHandler.invoke调用。
            Class<?> cl = getProxyClass0(loader, intfs);
            try {
                // 获取代理类构造函数
                final Constructor<?> cons = cl.getConstructor(constructorParams);
                final InvocationHandler ih = h;
                if (!Modifier.isPublic(cl.getModifiers())) {
                    cons.setAccessible(true);
                }
                // 返回代理类 对象
                return cons.newInstance(new Object[]{h});
            } catch (IllegalAccessException|InstantiationException e) {
                throw new InternalError(e.toString(), e);
            } catch (InvocationTargetException e) {
                Throwable t = e.getCause();
                if (t instanceof RuntimeException) {
                    throw (RuntimeException) t;
                } else {
                    throw new InternalError(t.toString(), t);
                }
            } catch (NoSuchMethodException e) {
                throw new InternalError(e.toString(), e);
            }
        }
    

    相关文章

      网友评论

        本文标题:java 反射 注解 代理

        本文链接:https://www.haomeiwen.com/subject/gooopctx.html