How to Obtain Annotations At Runtime Using Reflection in Java


Customize an annotation class by adding @retention (retentionpolicy.runtime), which means that the runtime exists and can be read by reflection. Next this example will show us how to get annotations at runtime using reflection.

Source Code

– MyAnn (Custom annotation)

package com.beginner.examples;

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

@Target(ElementType.FIELD) 			//The target is the field
@Retention(RetentionPolicy.RUNTIME) //The runtime exists and can be read by reflection
public @interface MyAnn {

	String value();
	
}

– User (Classes that use custom annotations)

package com.beginner.examples;

public class User {

	@MyAnn("User name")
	private String name;

	private int age;

	public User(String name, int age) {

		this.name = name;
		this.age = age;

	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}

– The test class

package com.beginner.examples;

import java.lang.reflect.Field;

public class GetAnnotationsUseReflect {

	public static void main(String[] args) {

		try {

			// Get the bytecode object for User
			Class c1 = Class.forName("com.beginner.examples.User");

			// Gets the name field object from the bytecode object
			Field field = c1.getDeclaredField("name");

			// Get comments from this field object
			MyAnn myAnn = field.getAnnotation(MyAnn.class);

			System.out.println(myAnn.value());

		} catch (Exception e) {

			e.printStackTrace();

		}

	}

}

Output:

User name

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments