I've been reading about annotations lately, and I'm a bit confused. I've used the annotation @NotNull but I don't really know how it checks if the variable is not null. No where in the code do I see anything checking values for null. That makes sense because it's an interface, so where does the actual processing happen and why isn't this location specified in the code? The examples I've seen usually just make an annotation that takes values, but doesn't do anything else, so I'm confused as to where the implementation occurs.
Annotation is just a metadata, no more no less. When you want to specify some details about the class you put annotations on it. Think about them (to some extent) as an alternative to the old well known XML way to define metadata.
Now, its obvious that someone reads your XML and runs the code that makes something with the metadata. The same happens with annotations: a framework to which annotation belongs to is responsible to read the annotation and make something with this information. In the case of @NotNull
, its hibernate-validator project. The API exposed by java allows to access the information in the annotations by reflection (the classes like java.lang.Class
, Method
, Field
, and so on). So somewhere inside hibernate validator there is a code that goes to your class, reads the annotations by reflection and checks whether the class adheres these annotations.
These annotation usually have retention policy 'runtime' which means that they're preserved in the bytecode and loaded along with the class that carries these annotations.
There are also annotations that should be processed by Java compiler. Like @Deprecated
, @SuppressWarnings
and so on. The benefit of having such annotation is that you can find some code issues during the compilation phase.
You can also put the annotation processors and 'plug' them during the compilation phase, buts its entirely different story.
Hope this clarifies a little the usage of annotations