Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Java Annotation #27

Open
wangbinyq opened this issue Nov 6, 2018 · 1 comment
Open

Java Annotation #27

wangbinyq opened this issue Nov 6, 2018 · 1 comment
Labels

Comments

@wangbinyq
Copy link
Owner

wangbinyq commented Nov 6, 2018

How Do Annotations Work in Java?

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
  • Annotations are only metadata and they do not contain any business logic.
  • It's the consumer's job to something using the metadata
  • @document - Whether to put the annotation in Javadocs
  • @retention - When the annotation is needed. Defines for how long the annotation should be kept.
    • RetentionPolicy.SOURCE - Discard during the compile.
    • RetentionPolicy.CLASS - Discard during class load. Bytecode-level post-processing. Default
    • RetentionPolicy.RUNTIME - Do not discard. Used for reflection at runtime.
  • @target? - Places the annotation can go.
    • Default to everywhere.
    • ElementType.TYPE (class, interface, enum)
    • ElementType.FIELD (instance field)
    • ElementType.(METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, ANNOTATION_TYPE, PACKAGE)
  • @inherited - Whether subclasses get the annotation
@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
Copy link
Owner Author

wangbinyq commented Nov 6, 2018

@wangbinyq wangbinyq added the note label Nov 28, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant