如何访问接收器类型参数的类型注释

How to access type annotations on a receiver type's parameters

我正在看一个相当琐碎的 class,它有一个定义带注释的 接收器类型的方法 :

class Foo<T> { 
  void foo(Foo<@Bar T> this) {}
}

我现在想访问接收器类型参数上的类型注释 @Bar 但是 Java 反射 API returns 访问接收器时带注释的原始类型:

assert Foo.class.getDeclaredMethod("foo")
                .getAnnotatedReceiverType() 
  instanceof AnnotatedParameterizedType;

断言失败,因为返回的注释类型作为原始类型返回 Foo。这是故意的吗?在访问返回的 AnnotatedType 实现的私有属性时,我仍然可以找到 @Bar 注释。

我是 运行 Java 8.

的最新版本

如果我运行这个:

Foo<Integer> f = new Foo<>();
Method m = f.getClass().getDeclaredMethod("foo");
AnnotatedType at = m.getAnnotatedReceiverType();
for (Annotation a:at.getAnnotations()) {
  System.out.println("Annotation: "+a);
}

然后我像这样在 Receiver Type 上添加注解:

  public void foo(@Bar(1) Foo<T> this) {}

现在您可以访问@Bar(1) 注释。请注意,我将注释直接放在 ReceiverParameter 上,而不是您想要的类型参数。

我知道这只是现在的部分答案...但我想从某个地方开始。其他人可能会添加并提供完整的答案,或者随着时间的推移我会学到更多......接收器类型和注释的这种使用对我来说都是非常新的,没有太多的文档和示例可以参考。

我怀疑根本无法访问此信息。另见 the answer an another topic:

As for the comments, about getting the annotation from a type argument in a method parameter, there's no way given the above.

同一主题将向您展示如何访问字段中类型参数的注释。

这是一个已知错误 JDK-8058220。然而,问题比看起来更严重。

如果不更改 class 文件格式和相应的规范更新,则无法轻松修复。当前 class 文件不包含区分接收器参数与常规参数所需的信息(参见 JDK-8062582)。

事实证明这是一个简单的错误。我首先想到,这是对链接问题的隐含,但类型注释与此无关。在 Java 运行时的当前实现中,类型注释的测试很差。在深入研究此事时,我发现了很多问题: