What happens when two different annotations have the same name? - java

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...

In such a case you need to specify the full qualified name, e.g
#bar.baz.Foo
#org.fubar.Foo
void myMethod() {...}

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.

They don't as the full package is part of the name. The effect is that you can only import one and will have to refer to any other with its fully qualified name. Like so
#NotNull
#com.jetbrains.annotations.NotNull
public Object ...

That won't matter since each annotation's full qualified name won't be the same. You can declare the qualified name on the import section.

The issue is the same for two classes/interafces/enums/annotations with the same name. They should appear in different packages. If they are in the same package (e.g. different versions) but different jar/directories, then the first one found in the classpath is chosen.

Related

Use shorter package names to resolve conflicting name

Is there a way to use a shortened package name in Java if you have conflicting names?
For instance, instead of typing out com.domain.a.b, if the conflict is in com.domain.a, you can just say b.SomeClass instead of com.domain.a.b.SomeClass. C# has a feature similar to this.
No, you either use fully qualified names or short names. You're probably looking for obscuring
A simple name may occur in contexts where it may potentially be
interpreted as the name of a variable, a type, or a package. In these
situations, the rules of ยง6.5 specify that a variable will be chosen
in preference to a type, and that a type will be chosen in preference
to a package. Thus, it is may sometimes be impossible to refer to a
visible type or package declaration via its simple name. We say that
such a declaration is obscured.
If you follow Java naming conventions, you shouldn't really have any issues.

What is the purpose of annotations in Java?

I understand that annotations serve a purpose to modify code without actually BEING code, such as:
#Author(
name = "Benjamin Franklin",
date = "3/27/2003"
)
But I don't understand how using the annotation is any better/ clearer/ more concise than just saying name = "Benjamin Franklin" ? How does the addition of annotations strengthen the code?
EDIT: Sorry for another questoin, but I know that #Override can help prevent/ track spelling mistakes when calling methods or classes, but how does it do that? Does it help the actual program at all?
Annotations are just metadata. On their own they serve little to no purpose. There must be an annotation processor, either at the compiler or run time level that uses them for something.
With an annotation like
#Author(
name = "Benjamin Franklin",
date = "3/27/2003"
)
for example, some annotation processor might read it with reflection at run time and create some log file that this author wrote whatever it's annotating on that date.
Annotations are metadata.
#Override annotation is used to make sure that you are overriding method of a superclass and not just making a method with the same name. Common mistakes here consist of:
spelling the method's name wrong
equal(Object o) instead of equals(Object o)
putting different set of arguments
MyString extends String { public boolean equals(MyString str) {} }
equals(MyString str) is not overriding the method equals(Object o) and therefore will not be used by standard Java comparators (which is used in some standard functions, such as List.contains() and this is prone to error situation).
This annotation helps compiler to ensure that you code everything correctly and in this way it helps program.
#Deprecated annotation doesn't make program not to compile but it makes developers think about using the code that can and/or will be removed in a future releases. So they (developers) would think about moving onto another (updated) set of functions. And if you compile your program with the flag -Xlint compilation process will return with an error unless you remove all usages of deprecated code or explicitly mark them with annotation #SuppressWarnings("deprecation").
#SuppressWarnings is used to suppress warnings (yes, I know it's Captain Obvious style :)). There is a deprecation suppression with #SuppressWarnings("deprecation"), unsafe type casting with #SuppressWarnings("unchecked") and some others. This is helpfull when your project compiler have a compilation flag -Xlint and you cannot (or don't want to) change that.
There are also annotation processors that you integrate into your program build process to ensure that program code meets some sort of criteria. For example with IntelliJ Idea IDE annotation processor you can use #Nullable and #NotNull annotations. They show other programmers when they use your code so that can transfer null as a certain parameter to a method or not. If they transfer null it will cause exception during compilation or before executing a single line method's code.
So annotations are quite helpful if you use them to their full potential.
Annotations are most likely used by other programs. Examples include:
#Override
IDE (compiler?) ensures that the signatures match
#Deprecated
IDE marks occurences, compiler warning
#FXML
JavaFX can use these annotations initialize variables in a controller class when an .fxml File is inflated (see http://docs.oracle.com/javafx/2/get_started/fxml_tutorial.htm). They are also used by JavaFX Scene Builder.
Annotations works as a way to marking up the code. Several frameworks uses it, and some others make a great use of it producing your own.
Besides, is important to understand that annotations are the equivalent to meta-data, but is much more than that, since it works as a tag language for the code.
Java #Annotation
#Annotation(from Java 5) adds a metadata which are used for instruction in compile, deployment and run time. It is defined by RetentionPolicy
RetentionPolicy defines a lifetime
RetentionPolicy.SOURCE: It is visible only in compile time(#Override, #SuppressWarnings, #StringDef). For example it can be used by apt to generate some code
RetentionPolicy.CLASS: It is visible in compile and deployment time(.class). For example it can be used by ASM or Java AOP paradigm like AspectJ
RetentionPolicy.RUNTIME: It is visible in deployment and run time. For example it can be used java reflection using getAnnotations(). Dagger 2 uses #Scope annotation
Create a custom Annotation
#Retention(<retention_policy>) //optional
#Target(<element_type>) //optional to specify Java element like, field, method...
#Inherited // optional will be visible by subclass
#Documented // optional will be visible by JavaDoc
#interface MyAnnotation {
//attributes:
String someName();
}
using
#MyAnnotation(someName = "Alex")
public class SomeClass {
}

How to indicate that member fields are #Nonnull by default?

My question is a follow-up to this one.
In past versions of FindBugs, it was possible to use #DefaultAnnotation(Nonnull.class) or #DefaultAnnotationForFields(Nonnull.class) to indicate that all fields in a package should be treated as #Nonnull. In the current version of FindBugs (2.0), #DefaultAnnotation and #DefaultAnnotationForFields are deprecated, and we should all use JSR-305 instead. But JSR-305 doesn't seem to cover everything the (now deprecated) FindBugs annotations cover.
The javadoc does suggest a number of alternatives:
#ParametersAreNonnullByDefault. This (obviously) only applies to parameters, not to member fields.
#CheckReturnValue, when applied to a type or package. Again, this doesn't apply to member fields.
#TypeQualifierDefault. Maybe this can do what I want, but I don't understand how it works, and I'm unable to find any documentation or examples on its usage or intent, besides some cryptic javadoc. I think it will help me create my own annotations, but can I be sure that all the tools (FindBugs, Eclipse, etc.) will interpret this new annotation correctly (or even at all)?
The javadoc doesn't provide any hints on how to deal with its deprecation.
So, using the current versions of FindBugs and/or JSR-305, how should I indicate that all member fields in a certain package (or even in a certain class) are supposed to be treated as #Nonnull? Is it even possible?
I had a similar question, and found that the following seems to work with findbugs (2.0.1-rc2)
Create a java file with the following annotation definition
#Nonnull
#TypeQualifierDefault(ElementType.FIELD)
#Retention(RetentionPolicy.RUNTIME)
public #interface FieldsAreNonNullByDefault
{
}
similarly, to enforce that all return values from a method are non-null
#Nonnull
#TypeQualifierDefault(ElementType.METHOD)
#Retention(RetentionPolicy.RUNTIME)
public #interface ReturnTypesAreNonNullByDefault
{
}
and then annotate the package as normal.
I used the following for my tests (package-info.java)
#javax.annotation.ParametersAreNonnullByDefault
#com.habit.lib.lang.FieldsAreNonNullByDefault
#com.habit.lib.lang.ReturnTypesAreNonNullByDefault
package com.mypackagename.subpkg;

Search for all instances of certain annotation type

Suppose I have this annotation
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.FIELD)
public #interface Name
{
String value();
}
This is going to be used as follows
#Name("name1")
public static Foo foo = new Foo();
I have multiples of these across my project source files. Is there an fairly simple way to search and collect all those "foo"s that're preceded by #Name?
In other words, I'd like to write a method that would return a Set<Foo> containing these.
Thanks!!!
I am not really familiar with the classpath scanners that others are suggesting. They seem like a robust - if not ideal - solution.
If you have control over the source, then you could use annotation processing.
Create an annotation processor that will create a class - MapClass with a static member Map<String,Foo>. Every time the annotation processor encounters the #Name annotation, it adds that to the source code of MapClass. When it finishes processing the annotations, it will have the same effect as if you hard coded the map.
Annotation processing happens during compile time. If some of the classes in your project are not compiled by you. For example, if someone else compiles some classes and gives a jar to you, then it won't work as easily. But if all the classes are compiled by you then it should not be a problem.
To create an annotation processor, extend AbstractProcessor. You will want to annotate your class with a # SupportedAnnotationTypes ( "Name" ) annotation (make sure name is the fully qualified name of your annotation.
Override the process method. process has two parameters: annotations and roundEnv. annotations is just the set of annotations that this particular processor supports - in your case it should be (Name). roundEnv is a useful utility class.
Iterate through the one annotation in annotations. Use roundEnv to getElementsAnnotatedWith. This should give you the set of all elements that carry the #Name annotation.
AbstractProcessor has another utility member - processingEnv. Use its getFiler method to createSourceFile.
Then you have to modify your compilation a little bit. You must compile your processor separately and before the other classes. After the processor is compiled and you are compiling the other classes you must tell the compiler about your processor. If you are using the command line you would add -processorpath /path/to/processor/class[es] and -processor qualified.name.of.processor.
The advantages of this approach over the class path scanner is that everything happens at compile time. So for example, if you accidentally add a #Name annotation to a Bar element, then you can have the processor throw a compile time error (if you wish the processor can ignore it). Then you can fix it before the product ships. With a class path scanner, any error thrown is a run time error - which the user will see.
The disadvantage of this approach is also that everything happens at compile time. This makes it harder to dynamically add classes to the project.
What you need is a Classpath scanner. I have used Metapossum Scanner (it won out because it is in the mvn repo) to scan for annotated Classes, but I do not think it would scan for annotated Fields.
The other option I looked into was Reflections. I have not used Reflections, only researched it. The documentation has a getFieldsAnnotatedWith query that seems like what you need.
Be forewarned, the Classpath scanners are slooow and get slooower the more you have in your Classpath.
No not really (not from code).
A solution would be to put them all in a class, and then iterate on the Fields (getFields()) of the class and check for Annotations (getAnnotation())
You may want to have a look at Scannotation! It may solve your problem!!!
Scannotation is a Java library that creates an annotation database from a set of .class files. This database is really just a set of maps that index what annotations are used and what classes are using them.
PS.: VRaptor framework uses it internally!

Annotation concepts in Java

To quote this link :
Some developers think that the Java compiler understands the tag and
work accordingly. This is not right. The tags actually have no meaning
to the Java compiler or runtime itself. There are tools that can
interpret these tags
.
If the information contained in the annotation is only metadata, why wont my code compile if I annotate wrongly ? That particular annotation should be simply ignored right ?
Edit :
Just to provide an example... A simple JAX-RS web service on Jersey uses an annotation like :
#Path("mypath")
Now, if I change this to :
#Paths("mypath")
OR
#Path(123)
it should NOT stop me from compiling the code according to the above link...
The article is wrong for at least some annotations. Thinks like #SuppressWarnings and #Override the compiler does have very specific knowledge. In fact, the article points this out itself:
Metadata is used by the compiler to perform some basic compile-time checking. For example there is a override annotation that lets you specify that a method overrides another method from a superclass.
Quite how it can be used by the compiler if "the tags actually have no meaning to the Java compiler", I don't know...
Additionally, even for annotations that the compiler doesn't attach any semantic meaning to, it will still verify that when you try to specify particular arguments etc, that those arguments have sensible names and types for the annotation you're using.
Annotations are basically a special form of interface, so the compiler has to be able to load the annotation definition in order to encode the information so it can be included in the class file. Once it's in the class file, the class loader will load it as part of the class, so that annotation-processing tools can access the information. The compiler will verify that only defined arguments are used, as well as supplying default values for attributes that aren't specified (and have defaults defined).

Categories

Resources