In Java, an annotation is a special kind of syntax that can be used to provide additional information about a program element, such as a class, method, or field. Annotations are defined using the @interface
keyword and can be applied to a program element using the @AnnotationName
syntax.
Here is an example of how to define and use an annotation in Java:
import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @interface Test { String value() default ""; } class Example { @Test public void testMethod() { // code goes here } }
In this example, the @Test
annotation is defined and applied to the testMethod
method. The @Retention
and @Target
annotations specify the retention policy and target elements for the @Test
annotation.
You can also define parameters for an annotation using the name()
syntax, for example:
@interface Test { String value() default ""; int timeout() default 1000; }
Annotations can be used to provide additional metadata about a program element, and can be accessed at runtime using reflection.