I don't know Java. I started learning Scala. I can't imagine what and what for annotations are? Could someone explain me?
Annotations are meta-data attached to classes/methods/fields and can be used by frameworks to determine required functionality surrounding those classes/methods/fields.
Common uses include:
- marking methods as unit-test methods and for associated set-up/tear-down (e.g. JUnit and TestNG)
- marking classes and fields for persistence (e.g. Hibernate)
- marking classes and fields to be exposed as JMX beans
Annotations are a Java feature, and as such available in Scala as well as Java.
Annotations, in general, make it possible to associate information with a definition e.g. the definition of a class, method or variable. Annotations can be used by the compiler or accessed by other parts of your program e.g. in Java:
@SuppressWarnings("deprecation")
void useADeprecatedMethod() {
someObj.someDeprecatedMethod();
}
Here, the @SuppressWarnings
annotation tells the compiler not to issue a warning about useADeprecatedMethod's
use of someDeprecatedMethod
.
Other uses in the Java world include adding information to a class regarding how it maps to a relational database for use by OR mappers like Hibernate.
In Scala, a number of things which are keywords or marker interfaces in Java are implemented as annotations in Scala. e.g. @throws
, @serializable
.
Here is an example showing Scala and Java working together with the help on an annotation. Imagine we're going to define a Person
class in Scala. When we come to use Person
in Java, the Java programmer will expect us to have setName
and getName
methods as is the bean convention in Java. This can be achieved using the @BeanProperty
annotation:
Person class in Scala:
class Person {
@BeanProperty
var name = "Joe Bloggs"
}
In Java:
public void printPerson(Person p) {
// Scala added the getName method for us
System.out.println(p.getName());
}
One interesting aspect of Java annotations is control over their retention. When an annotation type (a Java class that implements the Annotation
interface) is defined, one of its properties is its RetentionPolicy
, one of:
- SOURCE — Annotations are to be discarded by the compiler.
- CLASS — Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time.
- RUNTIME — Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively.