What are the major areas that we can use Annotations? Is the feature a replacement for XML based configuration?
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 ...;
}
}
The forthcoming JDK7 will allow annotations on any type. There are already proposals to use this feature for compiler annotations such as NotNull, like in:
public void processSomething(@NotNull String text) {
...
}
which might allow 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.
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 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 of 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 `@Text` 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.
-- Flaviu Cipcigan
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.
JEE 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.
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.
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"
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.
That is a very interesting question.
Annotations are meta-meta-object which can be used to describe other meta-object. Meta-object are class, field and method. 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 reflexion and meta-programming.
An annotation needs to be interpreted in one way or another to to be useful. Annotations can be interpreted at development-time by the IDE or the compiler or at run-time by a framework.
Annotation 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 case, an annotation is used to describe the element, which is frequently referred as its semantics.
Prior to JDK5, the information that is now contained in the 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 project Lombok, which uses annotation to define how to generate equals
or hashCode
methods.