What are the major areas that we can use Annotations? Is the feature a replacement for XML based configuration?
Annotations are meta-meta-objects which can be used to describe other meta-objects. Meta-objects are classes, fields and methods. Asking an object for its meta-object (e.g. anObj.getClass() ) is called introspection. The introspection can go further and we can ask a meta-object what are its annotations (e.g. aClass.getAnnotations). Introspection and annotations belong to what is called reflection and meta-programming.
An annotation needs to be interpreted in one way or another to be useful. Annotations can be interpreted at development-time by the IDE or the compiler, or at run-time by a framework.
Annotation processing is a very powerful mechanism and can be used in a lot of different ways:
to describe constraints or usage of an element: e.g. #Deprecated, #Override, or #NotNull
to describe the "nature" of an element, e.g. #Entity, #TestCase, #WebService
to describe the behavior of an element: #Statefull, #Transaction
to describe how to process the element: #Column, #XmlElement
In all cases, an annotation is used to describe the element and clarify its meaning.
Prior to JDK5, information that is now expressed with annotations needed to be stored somewhere else, and XML files were frequently used. But it is more convenient to use annotations because they will belong to the Java code itself, and are hence much easier to manipulate than XML.
Usage of annotations:
Documentation, e.g. XDoclet
Compilation
IDE
Testing framework, e.g. JUnit
IoC container e.g. as Spring
Serialization, e.g. XML
Aspect-oriented programming (AOP), e.g. Spring AOP
Application servers, e.g. EJB container, Web Service
Object-relational mapping (ORM), e.g. Hibernate, JPA
and many more...
...have a look for instance at the project Lombok, which uses annotations to define how to generate equals or hashCode methods.
There are mutiple applications for Java's annotations. First of all, they may used by the compiler (or compiler extensions). Consider for example the Override annotation:
class Foo {
#Override public boolean equals(Object other) {
return ...;
}
}
This one is actually built into the Java JDK. The compiler will signal an error, if some method is tagged with it, which does not override a method inherited from a base class. This annotation may be helpful in order to avoid the common mistake, where you actually intend to override a method, but fail to do so, because the signature given in your method does not match the signature of the method being overridden:
class Foo {
#Override public boolean equals(Foo other) { // Compiler signals an error for this one
return ...;
}
}
As of JDK7, annotations are allowed on any type. This feature can now be used for compiler annotations such as NotNull, like in:
public void processSomething(#NotNull String text) {
...
}
which allows the compiler to warn you about improper/unchecked uses of variables and null values.
Another more advanced application for annotations involves reflection and annotation processing at run-time. This is (I think) what you had in mind when you speak of annotations as "replacement for XML based configuration". This is the kind of annotation processing used, for example, by various frameworks and JCP standards (persistence, dependency injection, you name it) in order to provide the necessary meta-data and configuration information.
Annotations are a form of metadata (data about data) added to a Java source file. They are largely used by frameworks to simplify the integration of client code. A couple of real world examples off the top of my head:
JUnit 4 - you add the #Test annotation to each test method you want the JUnit runner to run. There are also additional annotations to do with setting up testing (like #Before and #BeforeClass). All these are processed by the JUnit runner, which runs the tests accordingly. You could say it's an replacement for XML configuration, but annotations are sometimes more powerful (they can use reflection, for example) and also they are closer to the code they are referencing to (the #Test annotation is right before the test method, so the purpose of that method is clear - serves as documentation as well). XML configuration on the other hand can be more complex and can include much more data than annotations can.
Terracotta - uses both annotations and XML configuration files. For example, the #Root annotation tells the Terracotta runtime that the annotated field is a root and its memory should be shared between VM instances. The XML configuration file is used to configure the server and tell it which classes to instrument.
Google Guice - an example would be the #Inject annotation, which when applied to a constructor makes the Guice runtime look for values for each parameter, based on the defined injectors. The #Inject annotation would be quite hard to replicate using XML configuration files, and its proximity to the constructor it references to is quite useful (imagine having to search to a huge XML file to find all the dependency injections you have set up).
Hopefully I've given you a flavour of how annotations are used in different frameworks.
Annotations in Java, provide a mean to describe classes, fields and methods. Essentially, they are a form of metadata added to a Java source file, they can't affect the semantics of a program directly. However, annotations can be read at run-time using Reflection & this process is known as Introspection. Then it could be used to modify classes, fields or methods.
This feature, is often exploited by Libraries & SDKs (hibernate, JUnit, Spring Framework) to simplify or reduce the amount of code that a programmer would unless do in orer to work with these Libraries or SDKs.Therefore, it's fair to say Annotations and Reflection work hand-in hand in Java.
We also get to limit the availability of an annotation to either compile-time or runtime.Below is a simple example on creating a custom annotation
Driver.java
package io.hamzeen;
import java.lang.annotation.Annotation;
public class Driver {
public static void main(String[] args) {
Class<TestAlpha> obj = TestAlpha.class;
if (obj.isAnnotationPresent(IssueInfo.class)) {
Annotation annotation = obj.getAnnotation(IssueInfo.class);
IssueInfo testerInfo = (IssueInfo) annotation;
System.out.printf("%nType: %s", testerInfo.type());
System.out.printf("%nReporter: %s", testerInfo.reporter());
System.out.printf("%nCreated On: %s%n%n",
testerInfo.created());
}
}
}
TestAlpha.java
package io.hamzeen;
import io.hamzeen.IssueInfo;
import io.hamzeen.IssueInfo.Type;
#IssueInfo(type = Type.IMPROVEMENT, reporter = "Hamzeen. H.")
public class TestAlpha {
}
IssueInfo.java
package io.hamzeen;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* #author Hamzeen. H.
* #created 10/01/2015
*
* IssueInfo annotation definition
*/
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.TYPE)
public #interface IssueInfo {
public enum Type {
BUG, IMPROVEMENT, FEATURE
}
Type type() default Type.BUG;
String reporter() default "Vimesh";
String created() default "10/01/2015";
}
Is it a replacement for XML based
configuration?
Not completely, but confguration that corresponds closely to code structures (such as JPA mappings or dependency injection in Spring) can often be replaced with annotations, and is then usually much less verbose, annoying and painful. Pretty much all notable frameworks have made this switch, though the old XML configuration usually remains as an option.
There are 2 views of annotations
user view, most of the time, annotations work like a shortcut, save you some key strokes, or make your program more readable
vendor view, the processor's view of annotation is more of light weighted 'interface', your program DOES confront to SOMETHING but without explicitly "implements" the particular interface(here aka the annotation)
e.g. in jpa you define something like
#Entity class Foo {...}
instead of
class Foo implements Entity {...}
both speak the same thing "Foo is an Entity class"
Where Annotations Can Be Used
Annotations can be applied to declarations: declarations of classes, fields, methods, and other program elements. When used on a declaration, each annotation often appears, by convention, on its own line.
Java SE 8 Update: annotations can also be applied to the use of types. Here are some examples:
Class instance creation expression:
new #Interned MyObject();
Type cast:
myString = (#NonNull String) str;
implements clause:
class UnmodifiableList implements
#Readonly List<#Readonly T> { ... }
Thrown exception declaration:
void monitorTemperature() throws
#Critical TemperatureException { ... }
Frameworks like Hibernate were lots of configuration/mapping is required uses Annotations heavily.
Take a look at Hibernate Annotations
JPA (from Java EE 5) is an excellent example of the (over)use of annotations. Java EE 6 will also introduce annotations in lot of new areas, such as RESTful webservices and new annotations for under each the good old Servlet API.
Here are several resources:
Sun - The Java Persistence API
Java EE 5 tutorial - JPA
Introducing the Java EE 6 platform (check all three pages).
It is not only the configuration specifics which are to / can be taken over by annotations, but they can also be used to control the behaviour. You see this good back in the Java EE 6's JAX-RS examples.
It is useful for annotating your classes, either at the method, class, or field level, something about that class that is not quite related to the class.
You could have your own annotations, used to mark certain classes as test-use only. It could simply be for documentation purposes, or you could enforce it by filtering it out during your compile of a production release candidate.
You could use annotations to store some meta data, like in a plugin framework, e.g., name of the plugin.
Its just another tool, its has many purposes.
Annotations may be used as an alternative to external configuration files, but cannot be considered a complete replacement. You can find many examples where annotationi have been used to replace configuration files, like Hibernate, JPA, EJB 3 and almost all the technologies included in Java EE.
Anyway this is not always good choice. The purpose of using configuration files is usually to separate the code from the details of the environment where the application is running. In such situations, and mostly when the configuration is used to map the application to the structure of an external system, annotation are not a good replacement for configuration file, as they bring you to include the details of the external system inside the source code of your application. Here external files are to be considered the best choice, otherwise you'll need to modify the source code and to recompile every time you change a relevant detail in the execution environment.
Annotations are much more suited to decorate the source code with extra information that instruct processing tools, both at compile time and at runtime, to handle classes and class structures in special way. #Override and JUnit's #Test are good examples of such a usage, already explained in detail in other answers.
In the end the rule is always the same: keep inside the source the things that change with the source, and keep outside the source the things that change independently from the source.
It attaches additional information about code by (a) compiler check or (b) code analysis
**
Following are the Built-in annotations:: 2 types
**
Type 1) Annotations applied to java code:
#Override // gives error if signature is wrong while overriding.
Public boolean equals (Object Obj)
#Deprecated // indicates the deprecated method
Public doSomething()....
#SuppressWarnings() // stops the warnings from printing while compiling.
SuppressWarnings({"unchecked","fallthrough"})
Type 2) Annotations applied to other annotations:
#Retention - Specifies how the marked annotation is stored—Whether in code only, compiled into the class, or available at run-time through reflection.
#Documented - Marks another annotation for inclusion in the documentation.
#Target - Marks another annotation to restrict what kind of java elements the annotation may be applied to
#Inherited - Marks another annotation to be inherited to subclasses of annotated class (by default annotations are not inherited to subclasses).
**
Custom Annotations::
**
http://en.wikipedia.org/wiki/Java_annotation#Custom_annotations
FOR BETTER UNDERSTANDING TRY BELOW LINK:ELABORATE WITH EXAMPLES
http://www.javabeat.net/2007/08/annotations-in-java-5-0/
Following are some of the places where you can use annotations.
a. Annotations can be used by compiler to detect errors and suppress warnings
b. Software tools can use annotations to generate code, xml files, documentation etc., For example, Javadoc use annotations while generating java documentation for your class.
c. Runtime processing of the application can be possible via annotations.
d. You can use annotations to describe the constraints (Ex: #Null, #NotNull, #Max, #Min, #Email).
e. Annotations can be used to describe type of an element. Ex: #Entity, #Repository, #Service, #Controller, #RestController, #Resource etc.,
f. Annotation can be used to specify the behaviour. Ex: #Transactional, #Stateful
g. Annotation are used to specify how to process an element. Ex: #Column, #Embeddable, #EmbeddedId
h. Test frameworks like junit and testing use annotations to define test cases (#Test), define test suites (#Suite) etc.,
i. AOP (Aspect Oriented programming) use annotations (#Before, #After, #Around etc.,)
j. ORM tools like Hibernate, Eclipselink use annotations
You can refer this link for more details on annotations.
You can refer this link to see how annotations are used to build simple test suite.
Java EE 5 favors the use of annotations over XML configuration. For example, in EJB3 the transaction attributes on an EJB method are specified using annotations. They even use annotations to mark POJOs as EJBs and to specify particular methods as lifecycle methods instead of requiring that implementation of an interface.
I have a requirement to create a custom Annotation which when applied over a method checks and validates the input parameters (Primitive and non-primitive) against various checks. And if checks fail should return a error message directly.
While searching I have come across use of AbstractProcessor and ConstraintValidator when we create a custom annotation. Being new to creating custom annotation, I would like to understand how to go ahead implementing my problem statement.
First of all, you need to understand that you're talking about two different things.
TL;DR: compile-time vs run-time - you need run-time
An Annotation processor is an abstract term to identify a process which runs during compile time, and which is able to scan the source files, the ones which have a .java extension.
The Annotation processor implementation might throw warnings, or even errors to stop the compilation task, based on arbitrary checks.
Example: "I noticed someone passed a null value to my method, it's a error! Stop everything!"
The starting point for implementing an Annotation processor is the AbstractProcessor base class, or the Processor interface (documentation).
You'd also need, unlike the ConstraintValidator implementation, to register it explicitly via a processor metadata file, which must be located under a standard directory inside the produced JAR artifact.
META-INF/services/javax.annotation.processing.Processor
What is needed to create an Annotation processor is already included in the standard JDK. You don't need external dependencies.
On the other hand, a ConstraintValidator identifies an interface which is shipped with the Validation API module, under the package javax.validation. There are different implementations of this API, but the most used one is Hibernate Validator (documentation).
The validation which this interface provides are verified at runtime.
Unlike the Annotation processor, the Validation API implementation must be provided manually, e.g.
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.15.Final</version>
</dependency>
You wrote
when applied over a method checks and validates the input parameters
(Primitive and non-primitive) against various checks
It seems you need to write run-time checks, which means the Validation API is the road to take.
The use cases of AbstractProcessor and ConstraintValidator are quite different. Let's take a dive and explore both.
The AbstractProcessor is
a convenient superclass for most concrete annotation processors
So what are annotation processors and what is their use case? If you want to generate new source code at compile time, based on annotations, you can use annotation processors. They are provided as part of the compilation process and invoked through the Java compiler. An example of this is a static metamodel geneartors for JPA.
A ConstraintValidator can be used to ensure, at runtime, that attributes, parameters and alike satisfy certain constraint. One of the most popular constraints is #NotNull. At runtime, some piece of code, a constraint validator, checks that all fields/parameters annotated with #NotNull actually are not null. If you want to write your own constraint, you need to write an annotatation, as well as a processor to satisfy your constraint. This tutorial on dzone.com outlines the process of creating a custom annotation and corresponding ConstraintValidator.
I have a VariableElement field that is annotated with a generated Annotation (which is why I can't use field.getAnnotation(annotationClass)). I need to get all parameters passed to this annotation.
Note that by "a generated Annotation" I mean that literally the Annotation class itself (not the annotated one) has been generated by an Annotation Processor. The field/class that is being annotated is in the handwritten source code.
It didn't look like it'd be that hard, so far I've come up with this:
for (AnnotationMirror annotation : field.getAnnotationMirrors()) {
Map<? extends ExecutableElement, ? extends AnnotationValue> annotationValueMap = annotation.getElementValues();
messager.printMessage(Diagnostic.Kind.WARNING, annotation.toString() + ":" + annotationValueMap.toString());
}
I thought this would do it, but the output for the field is the following:
#MyAnnotation:{}
So, the processor does recognize that the field is annotated, but I'm unable to access the passed parameters. Even though the field is definetely annotated and does pass parameters with the annotation (it has to, since the annotation defines required parameters and no defaults):
#MyAnnotation(max = 387, min = 66876, ...)
private Integer myField;
Here's the generated annotation code:
#Retention(RetentionPolicy.SOURCE)
#Target(ElementType.FIELD)
public #interface MyAnnotation {
int max();
boolean allowAuto();
int min();
}
I've clean-compiled the project multiple times, the processor never sees the values. What am I overlooking here? The processor can obviously see the annotation itself, yet the parameters passed to it are hidden.
Recall that annotation processors run as part of the compiler, in steps called "rounds". This process runs iteratively until there is no new code to compile, and then processors get one last chance to run (not necessary for this answer, but helpful for more context). Each round only the newly created types are directly given to the processor to examine.
What seems to be happening here is that during a round you are emitting a new annotation type, which should allow the processor to observe certain features about some code submitted to be compiled. However, any types created during a given round are not yet compiled until the next round begins.
For this question, we run into a conflict here - some Java sources are compiled which use an annotation that doesn't exist yet. The processor first creates the annotation, and then tries to read the newly-created annotation out of those partly-compiled sources. Unfortunately, until the annotation has been compiled, we can't actually read the annotation. Instead, we need to wait until the subsequent round (once the annotation itself has compiled), then go back to that class which has finished being compiled and examine it.
This can be implemented yourself without too much trouble, but the easiest way is often to rely on the google/auto project (specifically the auto-common library, see https://github.com/google/auto/tree/master/common), and extend their BasicAnnotationProcessor class. One of the nice features it supports is to automatically examine types and check if there are any compilation issues - if so, they are deferred until a later round so you can handle them without any type resolution issues.
Use getAnnotation(MyAnnotation.class) available from VariableElement
in your example code you can do this to get the min and max parameters
MyAnnotation myAnnotation= field.getAnnotation(MyAnnotation.class);
int max = myAnnotation.max();
int min = myAnnotation.min();
this will work unless the annotation members returns class/class[] value, in which you will get an exception if you try to get the value using this method.
more about how to get class literal values can be found on this answer
How to read a Class[] values from a nested annotation in an annotation processor
Or using annotation mirrors
for (AnnotationMirror annotation : field.getAnnotationMirrors()) {
Map<? extends ExecutableElement, ? extends AnnotationValue> annotationValueMap = annotation.getElementValues();
annotationValueMap.forEach((element, annotationValue) -> {
messager.printMessage(Diagnostic.Kind.WARNING, element.getSimpleName().toString() + ":" + annotationValue.getValue());
});
}
In case you have more than one annotation on the field then you can iterate over the annotation mirrors and use the check types.isSameType(annotationMirror.getAnnotationType(), elements.getTypeElement(MyAnnotation.class.getName()).asType()) to find the annotation you are interested in
Yes, you will not be able to instantiate a Class object for a type which is not available in your annotation processor's classloader, and may not even have been compiled into a class file yet at all. A similar problem exists for retrieving enum constants.
There are a few wrinkles to dealing with this sort of thing:
Any annotation value that is declared as an array might come to you at compile time either as a single value, or a list of values - so any code needs a path to handle both the list and non-list case - like this
What you get may be a generic type, and if you are generating Java code or similar that wants to insert a reference to Foo.class you need to get the erasure of that type, so you don't generate Foo<Bar>.class into your generated sources.
One of the places your annotation processor is going to get run is in an IDE, on broken code still being typed, so it is important to fail gracefully in the case that code elements that, you would think, can't possibly be missing or broken or unlikely values, are. In an IDE, your annotation processor may also be kept alive for a long time and reused, so it's important not to pile up objects modeling stuff that has already been generated and emitted.
FWIW, I wrote a library to solve this and related problems, which can be found on Maven central at the coordinates com.mastfrog:annotations-tools:2.8.3.4 (check for newer versions). The usage pattern is simple:
Instantiate an instance of AnnotationUtils in an override of the init() method of your annotation processor and store it in a field
Use it to, for example, resolve a Class<?>[] into a list of string class names that you can work with inside javac, and similar
It makes it pretty straightforward to write annotation processors that do not directly depending on the classes they processes at all - which means the annotation processors (and their dependency graphs!) be completely independent of what they process, and can depend on whatever libraries they like without forcing those dependencies into the dependency graph of any project that uses them - the most common pattern is someone writes some annotations and then puts the annotation processor in the same project, or even package, and so anything the annotation processor uses becomes a dependency of every consumer of the annotations, even though those dependencies will probably never be used at runtime at all. That, it seems to me, is an antipattern worth avoiding.
Hibernate Search, Hibernate, Struts2... I see more examples... In same examples I see the annotation on the field.. Other on the get/set method.. There are differences? Or is casual..
I hope that is not a stupid question!
Saluti!
Luigi
The difference depends on the annotation and how it is used. For example, in Spring you can use the #Controller annotation only on a class. This tells Spring that the class is a controller.
As far as methods are concerned, #RequestMapping is an annotation that goes on a method. For properties, you can have validation annotations like #NotNull (in Hibernate validator).
Annotations are definitely not casual; they carry meaning and can affect the way the code behaves.
From the Java documentation regarding annotations:
Annotations provide data about a
program that is not part of the
program itself. They have no direct
effect on the operation of the code
they annotate.
Annotations have a number of uses,
among them:
Information for the compiler — Annotations can be used by the
compiler to detect errors or suppress
warnings.
Compiler-time and deployment-time processing — Software tools can
process annotation information to
generate code, XML files, and so
forth.
Runtime processing — Some annotations are available to be
examined at runtime.
Annotations can be applied to a
program's declarations of classes,
fields, methods, and other program
elements.
You can specify what an annotation can annotate by specifying the the elements (using a #Target annotation) when you define your own annotation.
This really depends on the code that interprets the annotations. It can of course make a difference, but the annotations you are talking about are probably meant to annotate a "property", which is something that technically does not exist in Java.
Java has fields and methods, but these are used to simulate properties under the "Java Bean" conventions, i.e. you have a public setX() and a getX() method that often (but not always) write and read a private field x. They're tied together via a naming condition, not a language mechanism.
Because of that, most frameworks that use annotations for such properties (e.g. for persistence mapping or dependency injection) are flexible and allow you to annotate either the field or the get or set method.