Java的8注释上的实例创建 [英] Java 8 Annotations on Instance creation

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

问题描述

在的Javadoc注解,它指出以下可以在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.

推荐答案

应用实例的创建类似的注释新@Anno对象()是的不是的创建的对象的属性只(编译时)类型前pression的,但是。在运行时,对象的实际类型没有注释,就像它有可能会在实例创建指定没有泛型类型参数。

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)对象 @Anno(1)对象 @Anno(4)对象 @Anno(3)对象,并在本月底code相同的对象,即使是由两个不同的持有类型变量, @Anno(1)对象 @Anno(3)对象,在同一时间!

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语言本身他们有无意义,始终接受。并在运行时,实例的类型总是对象不是受着类型标注。

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提供了一些方法来查询已注解的类型的类和成员,其中包括参数声明和返回类型的方法,但你不能查询的类型注释前pression,你将不能够找出一个方法是否真的包含前pression,让适用于单独类型标注前pression。

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.

有可能是第三方库定居在字节code处理库将提供在运行时获得这些注释...

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天全站免登陆