`ElementType.FIELD`与`ElementType.TYPE_USE` [英] `ElementType.FIELD` vs `ElementType.TYPE_USE`

查看:1752
本文介绍了`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 :

创建类型注释以支持对Java的改进分析 程序以确保更强大的类型检查的方式. Java SE 8版本 不提供类型检查框架,但允许您编写 (或下载)作为一个或多个实现的类型检查框架 与Java结合使用的更多可插拔模块 编译器.

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)以便可以在运行时使用反射来检查此批注,如下所示:

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`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆