Java Tutorial
Operators
Flow Control
String
Number and Date
Built-in Classes
Array
Class and Object
Inheritance and Polymorphism
Exception Handling
Collections, Generics and Enumerations
Reflection
Input/Output Stream
Annotation
Java annotations are a way to add metadata to your code, which can be processed during compilation or at runtime. In this tutorial, you will learn how to create and use custom annotations for classes, methods, and fields in Java.
To define a custom annotation, use the @interface
keyword followed by the annotation's name. Here, we create three custom annotations: @ClassAnnotation
, @MethodAnnotation
, and @FieldAnnotation
:
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @interface ClassAnnotation { String value(); } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @interface MethodAnnotation { String value(); } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) @interface FieldAnnotation { String value(); }
Each annotation has a value
attribute and is defined with specific @Retention
and @Target
meta-annotations:
@Retention
specifies when the annotation should be available. In this case, we set it to RetentionPolicy.RUNTIME
so the annotation will be available during the runtime of the program.@Target
defines where the annotation can be applied. Here, we set the target to ElementType.TYPE
for the @ClassAnnotation
, ElementType.METHOD
for the @MethodAnnotation
, and ElementType.FIELD
for the @FieldAnnotation
.Now, let's create a class with the custom annotations applied to the class, a method, and a field:
@ClassAnnotation("This is a class annotation.") public class SampleClass { @FieldAnnotation("This is a field annotation.") private String sampleField = "Sample Field"; @MethodAnnotation("This is a method annotation.") public void sampleMethod() { System.out.println("This is a sample method."); } }
Next, we'll create a class with a main
method to process the custom annotations at runtime:
import java.lang.reflect.Field; import java.lang.reflect.Method; public class AnnotationProcessor { public static void main(String[] args) { // Get the SampleClass class object Class<?> sampleClass = SampleClass.class; // Process the class annotation if (sampleClass.isAnnotationPresent(ClassAnnotation.class)) { ClassAnnotation classAnnotation = sampleClass.getAnnotation(ClassAnnotation.class); System.out.println("Class Annotation: " + classAnnotation.value()); } // Process the field annotations for (Field field : sampleClass.getDeclaredFields()) { if (field.isAnnotationPresent(FieldAnnotation.class)) { FieldAnnotation fieldAnnotation = field.getAnnotation(FieldAnnotation.class); System.out.println("Field '" + field.getName() + "' Annotation: " + fieldAnnotation.value()); } } // Process the method annotations for (Method method : sampleClass.getDeclaredMethods()) { if (method.isAnnotationPresent(MethodAnnotation.class)) { MethodAnnotation methodAnnotation = method.getAnnotation(MethodAnnotation.class); System.out.println("Method '" + method.getName() + "' Annotation: " + methodAnnotation.value()); } } } }
Compile and run the AnnotationProcessor
class, and you should see the following output:
Class Annotation: This is a class annotation. Field 'sampleField' Annotation: This is a field annotation. Method 'sampleMethod' Annotation: This is a method annotation.
Field Annotations in Java Examples: Field annotations are annotations applied to fields within a class. They can be used to add metadata or trigger specific behaviors related to those fields.
public class Person { @NonNull private String name; // Other fields and methods }
Creating Class Annotations in Java:
Class annotations are annotations applied to the entire class. They are declared similarly to other annotations but are placed before the class
keyword.
@Entity public class Product { // Class implementation }
Java Method-level Annotations: Method-level annotations are annotations applied to methods. They can indicate special behaviors or provide additional information about the method.
public class Calculator { @Deprecated public int add(int a, int b) { return a + b; } }
Field-level Annotations in Java: Field-level annotations are annotations specifically applied to fields. They can be used to enforce constraints, define mappings, or provide additional information.
public class Book { @Column(name = "book_title") private String title; // Other fields and methods }
Built-in Annotations for Java Classes:
Java provides built-in annotations like @Override
, @Deprecated
, and @SuppressWarnings
that can be applied at the class level.
@SuppressWarnings("unchecked") public class MyClass { // Class implementation }
Field Annotations and Reflection in Java: Reflection allows you to inspect and manipulate annotated fields dynamically.
Field field = MyClass.class.getDeclaredField("fieldName"); MyAnnotation annotation = field.getAnnotation(MyAnnotation.class);
Custom Annotations on Methods in Java: You can create custom annotations and apply them to methods to express specific behaviors or requirements.
@Retryable(maxAttempts = 3) public void performOperation() { // Method implementation }
Annotation Targets for Java Methods:
The @Target
meta-annotation can be used to specify that an annotation is applicable to methods.
@Target(ElementType.METHOD) public @interface MyMethodAnnotation { // Annotation definition }
Annotation-based Configuration for Java Classes:
Annotations are commonly used for configuration, such as Spring's @Component
or Hibernate's @Entity
.
@Component public class MyComponent { // Class implementation }
Field-level Annotations and Validation in Java: Annotations can be used for validation purposes, ensuring that field values meet specific criteria.
public class User { @Size(min = 3, max = 20) private String username; // Other fields and methods }
Java Annotations for Class-level Metadata: Annotations on classes can provide metadata or configuration information at the class level.
@Controller public class MyController { // Class implementation }
Annotation-based Security for Java Methods: Annotations can be used to define security-related metadata on methods, specifying access control rules or permissions.
@RolesAllowed("ADMIN") public void performAdminTask() { // Method implementation }
Java Annotations for Method Parameters: Annotations can also be applied to method parameters to provide additional information or constraints.
public class MyService { public void process(@Validated InputData data) { // Method implementation } }