wangbinyq / personal-wiki

2 stars 0 forks source link

Java Annotation #27

Open wangbinyq opened 6 years ago

wangbinyq commented 6 years ago

How Do Annotations Work in Java?

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface Todo {
  public enum Priority {LOW, MEDIUM, HIGH}
  public enum Status {STARTED, NOT_STARTED}
  String author() default "Yash";
  Priority priority() default Priority.LOW;
  Status status() default Status.NOT_STARTED;
}
@Todo(priority = Todo.Priority.MEDIUM, author = "Yashwant", status = Todo.Status.STARTED)
public void incompleteMethod1() {
  //Some business logic is written
  //But it’s not complete yet
}
Class businessLogicClass = BusinessLogic.class;
for(Method method : businessLogicClass.getMethods()) {
  Todo todoAnnotation = (Todo)method.getAnnotation(Todo.class);
  if(todoAnnotation != null) {
    System.out.println(" Method Name : " + method.getName());
    System.out.println(" Author : " + todoAnnotation.author());
    System.out.println(" Priority : " + todoAnnotation.priority());
    System.out.println(" Status : " + todoAnnotation.status());
  }
}
wangbinyq commented 6 years ago

Annotations in Java JSR 330 Dependency Injection Annotations