How to Get All Annotations From a Class in Java


Here this example focuses on how to get all annotations from a class.

Source Code

– MyAnn_1 (Customize annotation classes)

package com.beginner.examples;

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


@Retention(RetentionPolicy.RUNTIME) // The runtime exists and can be read by reflection
public @interface MyAnn_1 {
	
	String name();
}

– MyAnn_2(Customize annotation classes)

java
package com.beginner.examples;

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

@Retention(RetentionPolicy.RUNTIME) // The runtime exists and can be read by reflection
public @interface MyAnn_2 {

	String sex();
}

– User (Classes that use custom annotations)

package com.beginner.examples;

public class User {

	private String name;

	private String sex;

	@MyAnn_1(name = "User name")
	@MyAnn_2(sex = "Male or female")
	public User(String name, String sex) {

		this.name = name;
		this.sex = sex;

	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public String getName() {
		return name;
	}

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

}

– The test class

package com.beginner.examples;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;

public class GetAllAnnotationsUseReflect {

	public static void main(String[] args) {

		try {

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

			// Get the construct object from the Class object
			Constructor constructor = c1.getConstructor(String.class,String.class);
			

			// Gets all the annotated objects for this construct object
			Annotation[] anns = constructor.getAnnotations();
			
			for(Annotation a:anns) {
				
				System.out.println(a);
				
			}

			

		} catch (Exception e) {

			e.printStackTrace();

		}

	}

}

Output:

@com.beginner.examples.MyAnn_1(name="User name")
@com.beginner.examples.MyAnn_2(sex="Male or female")

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments