gpt4 book ai didi

Java 8 : Class to AnnotatedType

转载 作者:太空狗 更新时间:2023-10-29 22:56:37 25 4
gpt4 key购买 nike

在 Java 8 中,Class 似乎获得了获取其父类(super class)及其超接口(interface)的 AnnotatedType View 的方法。

如何将 Class 转换为其自己的 AnnotatedType?这个问题有意义吗?

据我所知,AnnotatedType 有一个 Type,而不是一个 Type。不过,它是一个 AnnotatedElement;一切都非常困惑。

到目前为止,我已经搜索过 Javadocs 但没有结果。

最佳答案

于是我终于对AnnotatedType接口(interface)有了一个可以接受的理解。这是一个有效的 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 {
}

这打印

sun.reflect.annotation.AnnotatedTypeFactory$AnnotatedTypeBaseImpl@1d44bcfa
true
[@com.testing.Test$Custom()]
[@com.testing.Test$Custom()]

AnnotatedType界面态

AnnotatedType represents the potentially annotated use of a type in the program currently running in this VM.

Class#getAnnotatedSuperclass() javadoc 状态

Returns an AnnotatedType object that represents the use of a type to specify the superclass of the entity represented by this Class object.

我在 AnnotatedType javadoc 中将 potentially 设置为粗体,因为它清楚地表明不必注释类型用法。如果你有

public static class Bar {}
...
Bar.class.getAnnotatedSuperclass(); // returns Class instance for java.lang.Object

这是一个在 Java 7 及更低版本中不可能出现的用例,因为您无法注释类型用法 (see some examples here)。然而,在 Java 8 中,您可以这样做

public static class Foo extends @Custom Bar {

其中 Bar 类型用作父类(super class),其用法用 @Custom 注释。因此它是一个 AnnotatedType。因此,Foo.class.getAnnotatedSuperClass() 将为该用法返回一个 AnnotatedType 实例。

How can you convert a Class to its own AnnotatedType? Does that question even make sense?

这个问题没有意义。这是因为 Class 对象包含有关类的独立元数据。所谓自包含,是指可以从类的 .class 文件(或实际声明)中推断出的所有内容。您无法在其他任何地方推断出该类型的任何用法,因此它本身无法转换为任何 AnnotatedType

你可以拥有

public static class Foo extends @Custom Bar {}

public static class Zoom extends @Custom Bar {}

public static class Doing extends @Custom Bar {}

Bar 的上述每种用法都有一个 AnnotatedType 实例,但是您会选择哪个来转换一个 [Bar] Class 到它自己的 AnnotatedType

关于Java 8 : Class to AnnotatedType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20364236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com