Annotations
Annotations in Java provide metadata about the program. This tutorial will teach you how to use annotations.
Built-in Annotations
Java provides several built-in annotations:
@Override
– Indicates that a method is intended to override a method in a superclass.@Deprecated
– Indicates that a method is deprecated and should not be used.@SuppressWarnings
– Suppresses specific compiler warnings.
Creating Custom Annotations
You can create your own custom annotations by using the @interface
keyword:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
String value();
}
public class Main {
@MyAnnotation(value = "Hello, World!")
public void myMethod() {
System.out.println("This is my method.");
}
public static void main(String[] args) {
Main main = new Main();
main.myMethod();
}
}
Using Annotations with Reflection
You can use reflection to access annotation information at runtime:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
String value();
}
public class Main {
@MyAnnotation(value = "Hello, World!")
public void myMethod() {
System.out.println("This is my method.");
}
public static void main(String[] args) throws Exception {
Main main = new Main();
Method method = main.getClass().getMethod("myMethod");
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
System.out.println("Annotation value: " + annotation.value());
}
}
Continue exploring our intermediate tutorials to learn more about Java programming.