[Java] Annotation

Annotation definition

-If @interface is added, it will be defined as an annotation.

Annotation parameter definition

--Declaration of parameters when using annotations

TestAnnotation.java


public @interface TestAnnotation {
    String param1();
    String param2() default "defaultValue";
}

UserAnnotation.java


@TestAnnotation (param1="30", param2="100")
public UserAnnotation() {}

Annotation reference

--Refer to using reflection.

Reference class


    Class<?> c = UserAnnotation.class;
    for (Annotation a : c.getDeclaredAnnotations()) {
        System.out.println(a);
    }

Console output


@com.example.demo.com.annotation.TestAnnotation(param2=100, param1=30)

Meta annotation

TestAnnotation


@Documented
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation{}

--Annotation attached to an annotation. --Of these, the one prepared on the java side is called the standard meta annotation.
ex. Documented, Target, Retention, Ingerited

@Documented --Whether to include annotation description in Javadoc.

@Target --Define where to place annotations.

type Description
TYPE Class interface, enum, annotation
FIELD field
METHOD Method
ANNOTATION_TYPE Annotation type declaration

@Retantion ――How far will the annotation information be used?

type Description
SOURCE It is retained only on the source and deleted when the class file is created.
CLASS It can be retained in a class file, but it cannot be referenced when the application is executed.
RUNTIME Can be used even when the application is executed.
This is necessary if you want to refer to annotations in reflection.

@Inherited --Add annotation information to the subclass that declares the class.

Reference site

@Documented behavior https://qiita.com/opengl-8080/items/1cc996d9e8bb5c811567

What is @meta-annotation? https://www.techscore.com/tech/Java/JavaSE/JavaLanguage/7-3/

Recommended Posts

[Java] Annotation
History of Java annotation
Java
Java
[Java] Creation of original annotation
Java learning (0)
[Java] array
Java protected
[Java] Module
Java array
Studying Java ―― 9
Java scratch scratch
Java tips, tips
Java methods
Java method
Java array
[Java] ArrayDeque
java (method)
Java Day 2018
Java string
java (array)
Java static
Java serialization
java beginner 4
JAVA paid
Studying Java ―― 4
Java (set)
java shellsort
[Java] compareTo
Studying Java -5
java reflexes
java (interface)
☾ Java / Collection
Java array
Studying Java ―― 1
[Java] Array
[Java] Polymorphism
Read CSV in Java (Super CSV Annotation)
Studying Java # 0
Java review
java framework
Java features
[Java] Inheritance
FastScanner Java
Java features
java beginner 3
Java memo
java (encapsulation)
Java inheritance
[Java] Overload
Java basics
Decompile Java
java notes
java beginner
Java (add2)
JAVA (Map)
[java] interface
Java9 collection
Java basics
Java methods
Java diary