本文介绍了`ElementType.FIELD`与`ElementType.TYPE_USE`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I not fully understand the difference between annotating variable and annotating its type. Should I prefer type annotation over declaration annotation in this scenario?

@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中的类型注释主要用于支持更强的类型检查.

Type annotations in Java 8 are mainly around to support stronger type checking.

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

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

From your above example, you should use the @EmailField field annotation, and you should also add @Retention(RetentionPolicy.RUNTIME) so that you can use reflection to check for this annotation at runtime as follows:

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

这篇关于`ElementType.FIELD`与`ElementType.TYPE_USE`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 20:09