如何从代理类获取注释

如何从代理类获取注释

本文介绍了Java - 如何从代理类获取注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对代理类不太熟悉,也不知道 this("annotation") 是如何成为代理对象的.我可以从 Proxy 对象中检索注释吗?

I'm not really familiar with proxy class and I have no idea how does this("annotation") became a proxy object. Can I retrieve annotations from Proxy object?

public static void test(Annotation annotation) {
    System.out.println("ValidBoolean annotation len:" + ValidBoolean.class.getAnnotations().length);
    System.out.println(annotation.getClass().getName() + ":" + annotation.getClass().getAnnotations().length);
    if (annotation instanceof ValidBoolean) {
        ValidBoolean validBoolean = (ValidBoolean) annotation;
        System.out.println("[BOOLEAN]" + validBoolean.getClass().getName() + ":" + validBoolean.getClass().getAnnotations().length);
    }
}

结果是:

ValidBoolean annotation len:3
com.sun.proxy.$Proxy28:0
[BOOLEAN]com.sun.proxy.$Proxy28:0

推荐答案

我仍然没有真正理解这种代理机制.但是我可以通过annotation.annotationType()而不是annotation.getClass()得到Annotation真正的类,因为注解只是一个接口,所以annotation.getClass() 只会产生一个 Java Proxy 对象!

I'm still not really understanding this Proxy mechanism. But I can get Annotation real class by annotation.annotationType() rather than annotation.getClass(), because annotation is just an interface so annotation.getClass() will only produce a Java Proxy object!

看起来,Proxy 对象没有继承 Annotations,这是我学到的最重要的东西.

And it seems, Proxy object doesn't inherit Annotations, this is the most important thing i've learned.

这篇关于Java - 如何从代理类获取注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 13:34