Curriculum
Annotations in Java are a form of metadata that can be added to code elements such as classes, methods, and fields to provide additional information to the compiler, runtime, or other tools. Annotations are denoted by the @
symbol followed by the annotation name.
Here’s an example of using the built-in @Override
annotation in Java:
public class MyClass { @Override public String toString() { return "MyClass object"; } }
In this example, we’re using the @Override
annotation to indicate that the toString()
method of MyClass
overrides a method with the same name in its superclass. This annotation helps the compiler catch errors where a method is intended to override a superclass method but has a different signature.
In addition to built-in annotations, Java also allows you to define your own custom annotations. Custom annotations can be created using the @interface
keyword.
Here’s an example of creating a custom annotation in Java:
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MyAnnotation { String value() default ""; int count() default 0; }
In this example, we’re creating a custom annotation called MyAnnotation
that can be applied to methods. This annotation has two attributes: value
and count
. The value
attribute is a string that can be used to provide additional information about the annotated method, and the count
attribute is an integer that can be used to indicate how many times the method has been called.
Annotations in Java can have different retention policies, which determine how long the annotation will be retained. The three retention policies are:
SOURCE
: The annotation is retained only in the source code and is discarded by the compiler.CLASS
: The annotation is retained in the compiled class file but is not available at runtime.RUNTIME
: The annotation is retained in the compiled class file and is available at runtime.Annotations in Java can also have different targets, which determine which code elements the annotation can be applied to. The possible targets are:
TYPE
: The annotation can be applied to a class, interface, or enum.FIELD
: The annotation can be applied to a field.METHOD
: The annotation can be applied to a method.PARAMETER
: The annotation can be applied to a method parameter.CONSTRUCTOR
: The annotation can be applied to a constructor.LOCAL_VARIABLE
: The annotation can be applied to a local variable.ANNOTATION_TYPE
: The annotation can be applied to another annotation.PACKAGE
: The annotation can be applied to a package.Annotations in Java provide a way to add additional metadata to code elements such as classes, methods, and fields. They can be used to provide information to the compiler, runtime, or other tools. Java provides built-in annotations such as @Override
, as well as the ability to create custom annotations using the @interface
keyword. By understanding the rules and syntax of annotations, you can write more effective and maintainable Java code.