- Syntactic metadata
- Used for Class, Method, Parameter, Variable...
- Different scope for different purpose
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Tweezable {
}
- SOURCE
- CLASS
- RUNTIME
- TYPE
- FIELD
- METHOD
- PARAMETER
- CONSTRUCTOR
- LOCAL_VARIABLE
- ANNOTATION_TYPE
- PACKAGE
- Annotate in source code
- Compile
- Generate Code
Implement Simple Factory pattern
- Separate of Concerns
- Hide instantiate logic
- Communicate on interface
public interface Animal {
void bark();
}
public class Cat implements Animal {
@Override
public void bark() { }
}
public class Dog implements Animal {
@Override
public void bark() { }
}
public class AnimalFactory {
public static Animal createAnimal(String type) {
switch (type) {
case "cat":
return new Cat();
case "dog":
return new Dog();
}
throw new RuntimeException("not support type");
}
}
public class Test {
public static void main(String args) {
Animal cat = AnimalFactory.createAnimal("cat");
cat.bark();
}
}
Rewrite