@Annotations
Before Java 5
• transient
• comments & java doc (@deprecated)
• interfaces
Where to use?
• classes
• fields
• methods
• packages
• variables
• types ( from Java 8)
@NotNull String array1 [][];
String array2 @NotNull [][];
String array3 [] @NotNull[];
String @NotNull[][] array4;
String @NotNull [] @NotNull[] array5;
@NotNull String @NotNull[] @NotNull[] array6;
@NonNull String name;
List<@NonNull String> names;
class UnmodifiableList<T> implements @Readonly List<@Readonly T> {...}
email = (@Email String) input; new @Information MyObject();
void doSomething() throws @ImportantForMe MyException { ... }
Use cases
• Information for the compiler
• Documentation
• Code generation
• Runtime processing
@Retention
• SOURCE
• CLASS
• RUNTIME
@Target
• ANNOTATION_TYPE
• CONSTRUCTOR
• FIELD
• LOCAL_VARIABLE
• METHOD
• PACKAGE
• TYPE_USE (TYPE_PARAMETER & TYPE)
• @Deprecated
• @Inherited
• @Deprecated
• @SuppressWarnings
• @Override
• @SafeVarargs
Java 8
• @Repeatable
• @FunctionalInterface
Example
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.PARAMETER})
public @interface Option {
String value();
Class type() default String.class;
boolean hasArg() default true;
boolean isRequired() default false;
}
@Demo
@Metaphor
public interface Life extends Box<Chocolate> {
}
@Oxymoron
public interface DisassemblerFactory {
Disassembler createDisassembler();
}
@LOL @Facepalm
@WTF("just use Collections.reverse()")
@Booyah
private static <T> void invertOrdering(List<T> list) {
for (int i = 0; i < list.size() / 2; i++) {
int j = list.size() - 1 - i;
T item1 = list.get(i);
T item2 = list.get(j);
list.set(i, item2);
list.set(j, item1);
}
}
@Magic
public static int negate(int n) {
return new Byte((byte) 0xFF).hashCode()
/ (int) (short) 'uFFFF' * ~0
* Character.digit ('0', 0) * n
* (Integer.MAX_VALUE * 2 + 1)
/ (Byte.MIN_VALUE >> 7) * (~1 | 1);
}
public void
setBonusMultiplier(@ThisHadBetterNotBe(NEGATIVE)
double multiplier) {
this.multiplier = multiplier;
}
@ThisWouldBeOneLineIn(
language = "haskell"
toWit = "product [1..n]")
public int factorial(int n) {
int fac = 1;
for (int i = 1; i <= n; i++) {
fac *= i;
}
return fac;
}
@Thanks

Annotations