How to Create Custom Annotation in Java


Annotation is a feature introduced in JDK1.5 and later, at the same level as classes, interfaces, and enums. It can be declared in front of packages, classes, fields, methods, local variables, method parameters, etc. In this example, we can see how to create custom annotation in Java.

Source Code

package com.beginner.examples;

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

public class CustomAnnotationExample {

	@MyAnn(value = "Test string")
	private String testAnn;

	public static void main(String[] args) {
			
	}

}

@Target(ElementType.FIELD) // The target is the field
@interface MyAnn {

	public String value();

}

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments