Skip to content
Java

Annotations

Custom annotations and usage.

By EZ4Code Team
annotationannotation

Code

import java.lang.annotation.*;

// Define annotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyAnnotation {
    String value() default "";
    int priority() default 0;
}

// Use annotation
class MyClass {
    @MyAnnotation(value = "test", priority = 1)
    public void doSomething() {}
}

// Read annotation via reflection
for (var method : MyClass.class.getDeclaredMethods()) {
    if (method.isAnnotationPresent(MyAnnotation.class)) {
        MyAnnotation ann = method.getAnnotation(MyAnnotation.class);
        System.out.println(ann.value() + ":" + ann.priority());
    }
}

Explanation

Annotations provide metadata for code and can be read at runtime via reflection.

More Java Snippets