@Entity
@Override
void mySuperMethod() { ... }
@Author(
name = "Benjamin Franklin",
date = "3/27/2003"
)
class MyClass() { ... }
@SuppressWarnings(value = "unchecked")
void myMethod() { ... }
@SuppressWarnings("unchecked")
void myMethod() { ... }
@Author(name = "Jane Doe")
@EBook
class MyClass { ... }
Predefined Java Annotations : Override, SuppressWarnings
Custom Annotation types : EBook, Author
Java SE 8 Annotations
@Author(name = "Jane Doe")
@Author(name = "John Smith")
class MyClass { ... }
new @Interned MyObject();
myString = (@NonNull String) str;
class UnmodifiableList<T> implements @Readonly List<@Readonly T> { ... }
void monitorTemperature() throws @Critical TemperatureException { ... }
package okdevtv;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Name {
public String myName();
}
package okdevtv.java;
import okdevtv.Name;
public class Z {
@Name(myName = "Kenu")
public void something() {
System.out.println("Do something");
}
}
package okdevtv.java;
import okdevtv.Name;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class NameTest {
public static void main(String[] args) throws NoSuchMethodException, SecurityException {
final Method method = Z.class.getMethod("something");
if (method.isAnnotationPresent(Name.class)) {
final Annotation annotation = method.getAnnotation(Name.class);
final Name name = (Name) annotation;
System.out.println(name.myName()); // Prints Kenu
}
Z z = new Z();
try {
method.invoke(z);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
z.something();
}
}