Basics

  • They are used to provide meta data for my code.
  • They do not have any impact on the actual code, but they can be used to provide some extra info.
  • They are used for three purposes
    • Compiler Instructions
    • Build-time Instructions
    • Runtime Instructions
  • TODO: Read about Reflections
  • @Entity - This is what an annotation looks like
  • They can also have elements in them like @Entity(tableName = "vehicles")
  • They are placed above classes, interfaces, methods, etc.

Built-in Annotations

  • @Deprecated
    • Mark a class, method or file as deprecated meaning it should no longer be used
  • @Override
    • Used above methods that override methods in a superclass
    • If the method does not match a method in superclass, the compiler will give me errors.
  • @SuppressWarnings
    • Makes the compiler suppress warnings for a given method
  • @Contended
    • Help avoid False Sharing
    • TODO: Read about False Sharing

Creating my own Annotations

  • @interface MyAnnotation {
        String value() default "";
        String name();
        int age();
        String[] newNames();
    }
  • @Retention: This can be used to specify if my custom annotation should be available at runtime, for inspection via reflection. You use RUNTIME retention when you want your program to make decisions based on annotations while it is executing.

    • Imagine you have a class with 10 methods, but for a specific user (e.g., a “Free Tier” user), you don’t want them to run the deleteDatabase method or the exportCSV method. You could write hundreds of if statements, OR you could use an annotation.
      @Retention(RetentionPolicy.RUNTIME)
      @interface MyAnnotation {
      String value() default "";
      }
  • @Target: To specify which Java elements my custom annotation can be used to annotate @Target({ElementType.METHOD}) Types of ElementType:

    • ElementType.ANNOTATION_TYPE
    • ElementType.CONSTRUCTOR
    • ElementType.FIELD
    • ElementType.LOCAL_VARIABLE
    • ElementType.METHOD
    • ElementType.PACKAGE
    • ElementType.PARAMETER
    • ElementType.TYPE
    • ElementType.TYPE_PARAMETER
    • ElementType.TYPE_USE
  • @Inherited: A custom java annotation used in a class should be inherited by subclasses inheriting from that class.

  • @Documented: Signal to JavaDoc that my custom annotation should be visible in the JavaDoc for classes using it. TODO: What is JavaDoc? How does it work