gpt4 book ai didi

java - `ElementType.FIELD` 与 `ElementType.TYPE_USE`

转载 作者:行者123 更新时间:2023-11-29 04:44:17 25 4
gpt4 key购买 nike

我不完全理解注释变量和注释其类型之间的区别。在这种情况下,我应该更喜欢类型注释而不是声明注释吗?

@EmailField // can be used on String or Array/Collection of String-s
private String email;
private @EmailType String email2;
@EmailField
private List<@EmailType String> emails;

@Target(ElementType.TYPE_USE)
@interface EmailType {}

@Target(ElementType.FIELD)
@interface EmailField {}

最佳答案

Java 8 中的类型注解主要是为了支持更强的类型检查。

来自 https://docs.oracle.com/javase/tutorial/java/annotations/type_annotations.html :

Type annotations were created to support improved analysis of Java programs way of ensuring stronger type checking. The Java SE 8 release does not provide a type checking framework, but it allows you to write (or download) a type checking framework that is implemented as one or more pluggable modules that are used in conjunction with the Java compiler.

在你上面的例子中,你应该使用 @EmailField 字段注释,你还应该添加 @Retention(RetentionPolicy.RUNTIME) 这样你就可以使用反射来在运行时检查此注释,如下所示:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface EmailField {}

关于java - `ElementType.FIELD` 与 `ElementType.TYPE_USE`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37898797/

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