Is it a bug in Eclipse or why I can't annotate parameters with fully qualified type names (FQN) with @NonNull
?
import org.eclipse.jdt.annotation.NonNull;
public class Foo {
// No problem
public void bar(@NonNull String x) {
}
// Error: Type annotations are not allowed on type names used to access
// static members
public void baz(@NonNull java.lang.String x) {
}
}
This is not a bug in Eclipse. Instead, it has to do with the way annotation types are processed by the Java compiler. The explanation given below illustrates the issue.
First of all, the @NonNull
annotation can apply to any use of a type (it is annotated with @Target(ElementType.TYPE_USE)
). However, the type it applies to according to the Java Language Specification, is the type the annotation is closest to. This is not always what would be expected:
In the first case, the @NonNull
annotation applies to the use of the type String
, which is a valid type. As such, the annotation is valid.
In the second case, however, the annotation applies to java
, which is a package name. As such, it is not a valid type, so the annotation cannot apply here. This will result in a compile-time error.
The Java Language Specification (paragraph 9.7.4) states:
For example, assume an annotation type TA which is meta-annotated with just
@Target(ElementType.TYPE_USE)
. The terms@TA java.lang.Object
andjava.@TA lang.Object
are illegal because the simple name to which@TA
is closest is classified as a package name. On the other hand,java.lang.@TA
Object is legal.
From this we can conclude that @NonNull java.lang.String x
will not work, but
java.lang.@NonNull String x
will.
Also see The Java Language Specification, Chapter 9.7.4.
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