Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when two different annotations have the same name?

I never encountered the case and now I'm wondering: what happens when/if two different annotations have the same name? (I'll give here an example using an annotation provided by IntelliJ but the question is really generic so I'm not tagging it 'IntelliJ')

For example the first sentence here:

http://youtrack.jetbrains.net/issue/IDEABKL-4959

says:

Many libraries have their own @NotNull annotations (intellij, hibernate-validation, ..).

What happens exactly if I wanted to use, say, both IntelliJ's @NotNull and Hibernate's @NotNull? (once again @NotNull is just an example where I happen to find a clash)

Are they incompatible? If they're incompatible, is it for the whole project?

This is something I'm really not familiar with...

like image 939
Gugussee Avatar asked Jan 07 '11 14:01

Gugussee


People also ask

Can we apply two annotations together?

It is also possible to use multiple annotations on the same declaration: @Author(name = "Jane Doe") @EBook class MyClass { ... } If the annotations have the same type, then this is called a repeating annotation: @Author(name = "Jane Doe") @Author(name = "John Smith") class MyClass { ... }

What is repeating annotations in Java?

For compatibility reasons, repeating annotations are stored in a container annotation that is automatically generated by the Java compiler. In order for the compiler to do this, two declarations are required in your code.

Can you apply more than one annotation?

You can repeat an annotation anywhere that you would use a standard annotation. For compatibility reasons, repeating annotations are stored in a container annotation that is automatically generated by the Java compiler. In order for the compiler to do this, two declarations are required in your code.

Are annotations inherited?

Annotations, just like methods or fields, can be inherited between class hierarchies. If an annotation declaration is marked with @Inherited , then a class that extends another class with this annotation can inherit it.


2 Answers

In such a case you need to specify the full qualified name, e.g

@bar.baz.Foo 
@org.fubar.Foo
void myMethod() {...}
like image 86
Landei Avatar answered Oct 20 '22 12:10

Landei


There is no ambiguity, because the annotation's package name will be specified in an import or on the annotation itself.

JSR-305 addresses your specific example. It seeks a standard set of annotations, and refers specifically to FindBugs' and IntelliJ's nullability annotations.

Nullness annotations (e.g., @NonNull and @CheckForNull). Both FindBugs and IntelliJ already support their own versions of nullness annotations.

like image 42
Andy Thomas Avatar answered Oct 20 '22 12:10

Andy Thomas