How to create your own annotation in Java and get the value

I will introduce a sample program that creates your own annotation in Java and gets the value of the annotation.

environment

C:\>java -version
java version "1.8.0_231"
Java(TM) SE Runtime Environment (build 1.8.0_231-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.231-b11, mixed mode)

C:\>

1. Create your own annotation

This is a sample of self-made annotation. Here, the members have "name" and "value".

MyAnnotation.java


package test01;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)     // (1) @Control how much annotation information is retained in Retantion
@Target({                               // (2) @Target Controls what type of element the annotation can be added to
    ElementType.TYPE,
    ElementType.FIELD,
    ElementType.CONSTRUCTOR,
    ElementType.METHOD
})
public @interface MyAnnotation {        // (3)Create MyAnnotation
    String name();
    int value() default 0;
}

Specify to what stage the annotation information is retained by @ Retention in (1).

The following can be mainly set for @Retention.

value Description
RetentionPolicy.SOURCE Annotations are retained only at the source level and are ignored by the compiler.
RetentionPolicy.CLASS Annotations are retained by the compiler at compile time, but are ignored by the Java Virtual Machine (JVM).
RetentionPolicy.RUNTIME Annotations are retained by the JVM and can be used in the runtime environment.

Here, specify RetentionPolicy.RUNTIME.

Specify the location where the annotation can be applied with @ Target in (2).

The following can be mainly set for @ Target.

value Description
ElementType.TYPE Make it applicable to classes, interfaces, annotations, and enum types.
ElementType.FIELD Make it applicable to the field.
ElementType.CONSTRUCTOR Make it applicable to the constructor.
ElementType.METHOD Make it applicable to the method.

Here, specify ʻElementType.TYPE, ʻElementType.FIELD, ʻElementType.CONSTRUCTOR, and ʻElementType.METHOD in @ Target.

In (3), create an annotation with the name MyAnnotation. Set the members to name and value.

2. Annotate the class

Add your own MyAnnotation to the classes, fields, constructors and methods of the Sample class.

Sample.java


package test01;

@MyAnnotation(name="class", value=100)              // (1)Grant MyAnnotation to class
public class Sample {

    @MyAnnotation(name="field", value=200)          // (2)Grant MyAnnotation to field
    private String name;

    @MyAnnotation(name="constructor", value=300)    // (3)Add MyAnnotation to constructor
    public Sample() {}

    @MyAnnotation(name="method", value=400)         // (4)Give method MyAnnotation
    public void execute() {
        System.out.println("execute");
    }
}

(1) Add your own annotation (MyAnnotation) to the class. (2) Add your own annotation (MyAnnotation) to the field. (3) Add your own annotation (MyAnnotation) to the constructor. (4) Add your own annotation (MyAnnotation) to the method.

3. Get annotation and refer to

Main.java


package test01;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Main {

    public static void main(String[] args)
            throws ClassNotFoundException, NoSuchMethodException, NoSuchFieldException, SecurityException {

        // (1)Get the annotation (MyAnnotation) attached to the class
        Class<?> clazz = Class.forName("test01.Sample");
        MyAnnotation annoClass = (MyAnnotation) clazz.getAnnotation(MyAnnotation.class);
        System.out.println("class annotation : name=" + annoClass.name() + ", value=" + annoClass.value());

        // (2)Get the annotation (MyAnnotation) attached to the field
        Field field = clazz.getDeclaredField("name");
        MyAnnotation annoField = (MyAnnotation) field.getAnnotation(MyAnnotation.class);
        System.out.println("field annotation : name=" + annoField.name() + ", value=" + annoField.value());

        // (3)Get the annotation (MyAnnotation) attached to the constructor
        Constructor<?> cons = clazz.getConstructor();
        MyAnnotation annoCons = (MyAnnotation) cons.getAnnotation(MyAnnotation.class);
        System.out.println("constructor annotation : name=" + annoCons.name() + ", value=" + annoCons.value());

        // (4)Get the annotation (MyAnnotation) attached to the method
        Method method = clazz.getMethod("execute");
        MyAnnotation annoMethod = (MyAnnotation) method.getAnnotation(MyAnnotation.class);
        System.out.println("method annotation : name=" + annoMethod.name() + ", value=" + annoMethod.value());

    }
}

(1) Acquires and displays the contents of the annotation (MyAnnotation) attached to the Sample class. (2) Acquires and displays the contents of the annotation (MyAnnotation) attached to the field name of the Sample class. (3) Acquires and displays the contents of the annotation (MyAnnotation) attached to the constructor of the Sample class. (4) Acquires and displays the contents of the annotation (MyAnnotation) attached to the ʻexecute method of the Sample` class.

reference

Lesson: Annotations (The Java™ Tutorials < Learning the Java Language)


that's all

Recommended Posts

How to create your own annotation in Java and get the value
How to get the date in java
[Java] How to get the key and value stored in Map by iterative processing
How to get the value after "_" in Windows batch like Java -version
[Java] How to get the maximum value of HashMap
How to get the class name / method name running in Java
[Forge] How to register your own Entity and Entity Render in 1.13.2
[Java] How to get the current directory
[Java] How to convert from String to Path type and get the path
How to increment the value of Map in one line in Java
[Java] How to get and output standard input
[Java] How to get the current date and time and specify the display format
How to get Class from Element in Java
How to get and study java SE8 Gold
How to get the setting value (property value) from the database in Spring Framework
How to get the absolute path of a directory running in Java
[Java] How to get the redirected final URL
[Java] How to get the authority of the folder
I want to get the value in Ruby
Create your own shortcuts in Xcode to eliminate the hassle of pod install
Contemplation: How to take advantage of functional interfaces in your own functions (java)
How to create a Java environment in just 3 seconds
[Java] How to omit the private constructor in Lombok
Source used to get the redirect source URL in Java
How to create a data URI (base64) in Java
Java classes and instances to understand in the figure
[Ruby] How to get the tens place and the ones place
Create your own Java annotations
How to get the class name of the argument of LoggerFactory.getLogger when using SLF4J in Java
Java conditional branching: How to create and study switch statements
Difference between Java and JavaScript (how to find the average)
How to create a placeholder part to use in the IN clause
How to retrieve the hash value in an array in Ruby
How to call and use API in Java (Spring Boot)
Make your own simple server in Java and understand HTTP
How to develop and register a Sota app in Java
How to derive the last day of the month in Java
Differences in how to handle strings between Java and Perl
How to switch Java in the OpenJDK era on Mac
How to use Java HttpClient (Get)
How to learn JAVA in 7 days
How to get parameters in Spark
How to write comments in the schema definition file in GraphQL Java and reflect them in GraphQL and GraphQL Playground
Handle your own annotations in Java
Filter the Java No. 2 Optional list that was useful in business and get the first value
How to solve the problem when the value is not sent when the form is disabled in rails and sent
[Java] How to create a folder
How to use classes in Java?
[Ruby] How to get the value by specifying the key. Differences between hashes, symbols and fetch
How to concatenate strings in java
[Rails] How to get the URL of the transition source and redirect
[Swift5] How to get an array and the complement of arrays
How to create a new Gradle + Java + Jar project in Intellij 2016.03
How to output the value when there is an array in the array
How to get the id of PRIMAY KEY auto_incremented in MyBatis
How to install the language used in Ubuntu and how to build the environment
How to get boolean value with jQuery in rails simple form
How to get and add data from Firebase Firestore in Ruby
How to solve the unknown error when using slf4j in Java
How to encrypt and decrypt with RSA public key in Java
How to get JDK 11 on your mac in a comfortable way