I am looking at a rather trivial class with a single method that defines an annotated receiver type:
class Foo<T> {
void foo(Foo<@Bar T> this) {}
}
I would now like to access the type annotation on the receiver type's parameter @Bar
but the Java reflection API returns an annotated raw type when accessing the receiver:
assert Foo.class.getDeclaredMethod("foo")
.getAnnotatedReceiverType()
instanceof AnnotatedParameterizedType;
The assertion fails as the annotated type that is returned is returned as a raw type Foo
. Is this intentional? I can still find the @Bar
annotation when accessing private properties of the implementation of AnnotatedType
that is returned.
I am running a recent version of Java 8.
Type Annotations are annotations that can be placed anywhere you use a type. This includes the new operator, type casts, implements clauses and throws clauses. Type Annotations allow improved analysis of Java code and can ensure even stronger type checking.
With Java 8, annotations can now also be written on any use of a type such as types in declarations, generics, and casts: @Encrypted String data; List<@NonNull String> strings; myGraph = (@Immutable Graph) tmpGraph; At first glance, type annotations aren't the sexiest feature of the new Java release.
As of the Java SE 8 release, annotations can also be applied to any type use. This means that annotations can be used anywhere you use a type. A few examples of where types are used are class instance creation expressions (new), casts, implements clauses, and throws clauses.
Java 8 has included two new features repeating and type annotations in its prior annotations topic. In early Java versions, you can apply annotations only to declarations. After releasing of Java SE 8 , annotations can be applied to any type use. It means that annotations can be used anywhere you use a type.
This is a known bug JDK-8058220. However, the problem is deeper that it may seem.
It cannot be easily fixed without changes to class file format and corresponding specification updates. Currently the class file does not contain information required to distinguish receiver parameter from a regular one (see JDK-8062582).
Turns out this is a simple bug. I first thought, this is an implicitation of the linked issues but type annotations have nothing to do with that. Type annotations are poorly tested in the current implementation of the Java runtime. I found a sheer number of issues when deep diving into the matter:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With