I made an annotation in Java.

Introduction

I was working and realized that I didn't understand annotations. I understand that @Override, @Duplicate, @Test are given, but I don't know how it works, so I looked it up.

environment

What are annotations in Java?

The following is from wikipedia.

Java annotation is a function to enter additional information as metadata for classes, methods, and packages, and was added in Java SE 5. Annotations can also be created by implementing the java.lang.annotation.Annotation interface.

Types of annotations in Java

The types of annotation are classified into the following three types.

--Marker annotation – Annotation with no data and only a name. Example: @Override, @Duplicate --Single value annotation – Annotation that has only one data. It looks like a method call. Example: @SuppressWarnings --Full annotation – Annotation with multiple data.

Make it more familiar than learning

Create annotation class

Info.java


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

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Info {
	String value();
}

To define the annotation class, add the following annotations.

CLASS: Recorded in the class file at compile time. Not loaded into the VM at run time. RUNTIME: Loaded into the VM at run time SOURCE: Discard at compile time

ʻANNOTATION_TYPE: Applicable to annotations CONSTRUCTOR: Applicable to constructor FIELD: Applicable to fields LOCAL_VARIABLE: Applicable locally METHOD: Applicable to methods PACKAGE: Applicable to packages PARAMETER`: Applicable to arguments

This time, I want to create a process to get the annotation value when executing the method, so Specify @Retention as RUNTIME and @Target as METHOD.

Create annotation class and call class

It will be the class to call. Add the created Info annotation to the method.

AnnotationInstance.java


public class AnnotationInstance {
	@Info("hoge")
	public void execute() {
		System.out.println("Hello World!!");
	}
}

@Info("hoge") The value is set in the @Info annotation. hoge is set in value.

It will be the calling main class.

AnnotationMain.java


import java.lang.reflect.Method;

public class AnnotationMain {

	public static void main(String[] args) {
		try {
			Class<?> clazz = Class.forName("AnnotationInstance");
			Method method1 = clazz.getMethod("execute", new Class<?>[] {});
			Info info1 = method1.getAnnotation(Info.class);
			System.out.println(info1.value());
		} catch (ClassNotFoundException | NoSuchMethodException | SecurityException e) {
			e.printStackTrace();
		}
	}
}

Get the method by reflection, and then get the annotation class.

I will try to run

Executing the ʻAnnotationMain.java` class created above will output the following result.

Execution result
hoge

It was confirmed that the value of the @Info annotation specified in the ʻexecute () method of ʻAnnotationInstance was acquired.

at the end

It was surprisingly easy to use. In the process of writing this article, I revisited some implementations of annotation classes. I don't usually touch it, but I think it's used because it's a framework and package development. I haven't been able to read it until now, so I'll read it without feeling weak in the future. I also touched the reflection for the first time in a while. I don't really understand that either, so I'll take a closer look.

Referenced site

Annotation-Wikipedia https://ja.wikipedia.org/wiki/%E3%82%A2%E3%83%8E%E3%83%86%E3%83%BC%E3%82%B7%E3%83%A7%E3%83%B3#Java%E3%81%AB%E3%81%8A%E3%81%91%E3%82%8B%E3%82%A2%E3%83%8E%E3%83%86%E3%83%BC%E3%82%B7%E3%83%A7%E3%83%B3 A little special Java annotation-Qiita https://qiita.com/kashira2339/items/6450714e42c37b441514 Sample to create your own annotation and get the value | ITSakura https://itsakura.com/java-annotation-make

Recommended Posts

I made an annotation in Java.
I made roulette in Java.
I sent an email in Java
I made a primality test program in Java
I want to send an email in Java.
I made a rock-paper-scissors game in Java (CLI)
I tried metaprogramming in Java
I wrote about Java downcast in an easy-to-understand manner
I tried using an extended for statement in Java
[Java] Annotation
I made an interpreter (compiler?) With about 80 lines in Ruby.
I created a PDF in Java.
I made a shopify app @java
[Beginner] I made a program to sell cakes in Java
Read CSV in Java (Super CSV Annotation)
[Java] Annotation
Try an If expression in Java
I wrote Goldbach's theorem in java
I tried using JWT in Java
Age guessing game made in Java
Sample vending machine made in Java
Run an application made with Java8 with Java6
Run an external process in Java
I made the "Sunshine Ikezaki game" I saw on Twitter in Java.
[Java] I participated in ABC-188 of Atcorder.
I made an eco server with scala
Sample vending machine made in Java (classification)
I did OpenCV camera calibration in Java
I made a new Java deployment tool
[* Java *] I participated in JJUG CCC 2019 Spring
I made StringUtils.isBlank
Changes in Java 11
Rock-paper-scissors in Java
I want to ForEach an array with a Lambda expression in Java
Pi in Java
FizzBuzz in Java
Refactored GUI tools made with Java8 + JavaFX in 2016
I made an app for myself! (Reading management app)
Second decoction: Try an If expression in Java
I tried to implement deep learning in Java
I made an Android app for MiRm service
I wrote a primality test program in Java
I made a Ruby extension library in C
rsync4j --I want to touch rsync in Java.
What I learned in Java (Part 2) What are variables?
How to solve an Expression Problem in Java
I tried to develop an application in 2 languages
I tried to create Alexa skill in Java
I wrote a prime factorization program in Java
[java] sort in list
Read JSON in Java
Make Blackjack in Java
I made an iPhone Theremin with Vision framework + AudioKit
Constraint programming in Java
Put java8 in centos7
I want to do something like "cls" in Java
NVL-ish guy in Java
Combine arrays in Java
"Hello World" in Java
Callable Interface in Java
I tried to implement Firebase push notification in Java