In Java, you can create custom annotations by defining a new interface that extends the java.lang.annotation.Annotation
interface.
Here is an example of how to create a custom annotation in Java:
import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; // Define the custom annotation @Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation { String value(); }cruoSe:www.lautturi.com
In this example, we define a custom annotation called MyAnnotation
that has a single element called value
. The @Retention
annotation specifies that the annotation should be retained at runtime, which means that it can be accessed using reflection.
To use the custom annotation, you can annotate class, method, or field declarations with it. For example:
@MyAnnotation("Hello, World!") public class Main { @MyAnnotation("Foo") public static void main(String[] args) { @MyAnnotation("Bar") int x = 10; } }
In this example, we annotate the Main
class, the main
method, and the x
field with the MyAnnotation
annotation.
To access the annotation at runtime, you can use the java.lang.reflect.AnnotatedElement
interface and its related classes. For example:
import java.lang.reflect.AnnotatedElement; public class Main { public static void main(String[] args) { // Get the Main class Class<Main> cls = Main.class; // Check if the Main class is annotated with the MyAnnotation annotation if (cls.isAnnotationPresent(MyAnnotation.class)) { // Get the MyAnnotation annotation MyAnnotation annotation = cls.getAnnotation(MyAnnotation.class); // Get the value of the annotation's value element String value = annotation.value(); // Print the value System.out.println(value); // Output: Hello, World! } } }