to include elements
@Author(
name = "Benjamin Franklin",
date = "3/27/2003"
)
class MyClass() { ... }
or one named value
@SuppressWarnings("unchecked")
void myMethod() { ... }
if no element,
@Override
void hello(){...}
You can have two aannotations with same name. (Java 8 or latter versions)
@Author(name = "Jane Doe")
@Author(name = "John Smith")
class MyClass { ... }
lass instance creation expression:
new @Interned MyObject(); Type cast:
myString = (@NonNull String) str; implements clause:
class UnmodifiableList<T> implements
@Readonly List<@Readonly T> { ... } Thrown exception declaration:
void monitorTemperature() throws
@Critical TemperatureException { ... }
Annotation types are a form of interface.
@interface ClassPreamble {
String author();
String date();
int currentRevision() default 1;
String lastModified() default "N/A";
String lastModifiedBy() default "N/A";
// Note use of array
String[] reviewers();
}
The body of the previous annotation definition contains annotation type element declarations, which look a lot like methods. Note that they can define optional default values.
This ```@ClassPreamble`` is used as:
After the annotation type is defined, you can use annotations of that type, with the values filled in, like this:
@ClassPreamble (
author = "John Doe",
date = "3/17/2002",
currentRevision = 6,
lastModified = "4/12/2004",
lastModifiedBy = "Jane Doe",
// Note array notation
reviewers = {"Alice", "Bob", "Cindy"}
)
public class Generation3List extends Generation2List {
// class code goes here
}
To Include your annotion in Javadoc-generated documentation :
// import this to use @Documented
import java.lang.annotation.*;
@Documented
@interface ClassPreamble {
// Annotation element definitions
}
There are several methods available in the Reflection API that can be used to retrieve annotations. The behavior of the methods that return a single annotation, such as AnnotatedElement.getAnnotationByType(Class
Ref: Orcale
Jiayang, Sun 27 April 2016