在Java 8中,Class
似乎已经获得了获取AnnotatedType
其超类及其超接口的视图的方法.
你如何将a转换Class
为自己的 AnnotatedType
?这个问题甚至有意义吗?
据我所知,a AnnotatedType
-a Type
,not is-a Type
.AnnotatedElement
不过,这是一个; 这一切都非常混乱.
到目前为止,我已经搜索过Javadocs无济于事.
Sot*_*lis 10
所以我终于对AnnotatedType
界面有了可接受的理解.这是一个有效的Java 8示例,用于说明其用途之一
public static void main(String[] args) {
Class<?> fooClass = Foo.class;
AnnotatedType type = fooClass.getAnnotatedSuperclass();
System.out.println(type);
System.out.println(Bar.class == type.getType());
System.out.println(Arrays.toString(type.getAnnotations()));
System.out.println(Arrays.toString(type.getDeclaredAnnotations()));
}
public static class Bar {
}
public static class Foo extends @Custom Bar {
}
// So that annotation metadata is available at run time
@Retention(RetentionPolicy.RUNTIME)
// TYPE_USE being the important one
@Target(value = {ANNOTATION_TYPE, CONSTRUCTOR, FIELD, LOCAL_VARIABLE,
METHOD, PACKAGE, PARAMETER, TYPE, TYPE_PARAMETER, TYPE_USE})
public @interface Custom {
}
Run Code Online (Sandbox Code Playgroud)
这打印
sun.reflect.annotation.AnnotatedTypeFactory$AnnotatedTypeBaseImpl@1d44bcfa
true
[@com.testing.Test$Custom()]
[@com.testing.Test$Custom()]
Run Code Online (Sandbox Code Playgroud)
该AnnotatedType
界面态
AnnotatedType
表示当前在此VM中运行的程序中可能带注释的类型的使用.
和Class#getAnnotatedSuperclass()
贾瓦多克州
返回一个
AnnotatedType
对象,该对象表示使用类型来指定此Class
对象所表示的实体的超类.
我在javadoc中做了可能的粗体,AnnotatedType
因为它清楚地表明类型用法不需要注释.如果你有
public static class Bar {}
...
Bar.class.getAnnotatedSuperclass(); // returns Class instance for java.lang.Object
Run Code Online (Sandbox Code Playgroud)
这是一个在Java 7及更低版本中无法实现的用例,因为您无法注释类型用法(请参阅此处的一些示例).但是,在Java 8中,您可以这样做
public static class Foo extends @Custom Bar {
Run Code Online (Sandbox Code Playgroud)
其中类型Bar
用作超类,其用法用注释@Custom
.因此它是一个AnnotatedType
.因此,Foo.class.getAnnotatedSuperClass()
将返回AnnotatedType
该用法的实例.
你如何将a转换
Class
为自己的AnnotatedType
?这个问题甚至有意义吗?
这个问题没有意义.这是因为Class
对象包含有关类的自包含元数据.通过自包含,我指的是可以从类的.class
文件(或实际声明)中推断出的所有内容.您无法在其他任何地方推断出任何类型的用法,因此无法将其转换为任何AnnotatedType
用途.
你可以有
public static class Foo extends @Custom Bar {}
public static class Zoom extends @Custom Bar {}
public static class Doing extends @Custom Bar {}
Run Code Online (Sandbox Code Playgroud)
AnnotatedType
上面的每个用法都有一个实例Bar
,但你会选择哪一个将[Bar]转换为Class
自己的AnnotatedType
?
归档时间: |
|
查看次数: |
2013 次 |
最近记录: |