How to Assign Default Values to Custom Annotations in Java


In this example we will show how to assign default values to custom annotations. We need first customize an annotation class and add default values for each entry, just as shown below.

Source Code

– MyAnn

package com.beginner.examples;

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

@Retention(RetentionPolicy.RUNTIME) //Add this annotation in order to also exist at runtime
public @interface MyAnn {
	
	String key() default "Default value for key";
	
	String value() default "Default value";

}

– UseMyAnn

package com.beginner.examples;

@MyAnn()
public class UseMyAnn {

}

– Test

package com.beginner.examples;

public class Test {

	public static void main(String[] args) {

		try {

			Class class1 = Class.forName("com.beginner.examples.UseMyAnn");

			
			MyAnn ann = class1.getAnnotation(MyAnn.class);

			System.out.println("key : " + ann.key());
			System.out.println("value : " + ann.value());
			
		} catch (Exception e) {

			e.printStackTrace();
		}

	}

}

Output:

key : Default value for key
value : Default value

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments