Java 8 实例创建注解 [英] Java 8 Annotations on Instance creation

查看:23
本文介绍了Java 8 实例创建注解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Javadocs for Annotations 中,它指出以下内容可以用 Java 8 编写:

In the Javadocs for Annotations, it states that the following can be written in Java 8:

new @Interned MyObject();

无论如何可以通过反射从像这样注释的对象中检索注释@Interned?我熟悉从方法、字段、类等中检索注释的典型方法,但我想知道是否可以在 Java 8 中在运行时将特定实例与注释相关联.

Is there anyway to retrieve the annotation @Interned from an object annotated like this via reflection? I'm familiar with the typical ways of retrieving annotations from methods, fields, classes, etc, but I'd like to know if it's possible to associate a particular instance with an annotation at runtime in Java 8.

推荐答案

应用于实例创建的注解,如 new @Anno Object() not not创建的对象,但仅限于 new 表达式的(编译时)类型.在运行时,对象的实际类型没有注释,就像它没有您可能在创建实例时指定的通用类型参数一样.

An annotation applied to an instance creation like new @Anno Object() is not a property of the created object but only of the (compile-time) type of the new expression. At runtime the actual type of the object does not have the annotation just like it has no Generic type parameters you might have specified at the instance creation.

请考虑以下示例:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE_USE)
@interface Anno { int value(); }

@Anno(1) Object o=new @Anno(2) Object();
@Anno(3) Object p=(@Anno(4) Object)o;

这里,简单的对象经历了几次类型变化,从@Anno(2) Object@Anno(1) Object@Anno(4)) Object@Anno(3) Object 并且在这段代码的末尾,同一个对象甚至被两个不同类型的变量保存,@Anno(1) Objectcode> 和 @Anno(3) Object,同时!

Here, the simple object goes through several type changes, from @Anno(2) Object to @Anno(1) Object to @Anno(4) Object to @Anno(3) Object and at the end of this code the same object is even held by two differently typed variables, @Anno(1) Object and @Anno(3) Object, at the same time!

您可以使用审计工具来验证这些类型转换对于 @Anno 暗示的任何语义是否合法,但对于 Java 语言本身而言,它们没有任何意义并且将始终被接受.并且在运行时,实例的类型永远是Object,不受类型注解的影响.

You may use audit tools to verify whether these type transitions are legal in respect to whatever semantics @Anno implies, but to the Java language itself they have no meaning and will be always accepted. And at runtime, the type of the instance will always be Object not being affected by the type annotation.

反射 API 提供了查询类和成员声明的注释类型的方法,包括方法的参数和返回类型,但您不能查询 new 表达式的类型注释,因为您不会能够找出方法是否实际包含 new 表达式,更不用说应用于该 new 表达式的类型注释.

The Reflection API provides ways to query the annotated types of declarations of classes and members which includes parameter and return types of methods but you cannot query the type annotations of a new expression as you will not be able to find out whether a method actually contains a new expression, let alone type annotations applied to that new expression.

可能会有 3rd 方库解决字节码处理库,它们将在运行时提供对这些注释的访问......

There might be 3rd party libraries settling on byte code processing libraries which will provide access to these annotations at runtime…

这篇关于Java 8 实例创建注解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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