VOOZH about

URL: https://www.geeksforgeeks.org/java/customize-java-annotation-with-examples/

⇱ Customize Java Annotation with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Customize Java Annotation with Examples

Last Updated : 23 Jul, 2025

Java annotations are a mechanism for adding metadata information to our source code (Program). They are a powerful part of Java that was added to JDK5. Annotations provide an alternative to the use of XML descriptors. Also, we are able to attach them to packages, classes, interfaces, methods, and fields, annotations by themselves have no effect on the execution of a source code (Program). In this article, we are going to focus on how to create and process custom annotations. We can  read in detail about how to customize the Java annotations with Example

Create Custom Annotation

We are going to create three custom annotations with the goal of serializing an object into a JSON string. that is -

  • Class Level Annotation
  • Field Level Annotation
  • Method Level Annotation

1. Class Level Annotation

The first step to creating a custom annotation is to declare it using the @interface keyword :

public @interface GFG {
}

The next step is to specify the scope and the target of our custom annotation :

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.Type)
public @interface GFG {
}

2. Field Level Annotation

Using the same fashion, we create our second annotation to mark the fields that we are going to include in the generated JSON :

3. Method Level Annotation

To serialize an object to a JSON string, we want to execute some method to initialize an object. For that reason, we are going to create an annotation to mark this method. First of All, declared a public annotation with runtime visibility that we can apply to our classes methods.


Example

Usage:

Annotated Class

Runnable Code


Output:

Java Custom Annotation Example

field name: id
field value: 112
field type: class java.lang.Long
is primary: true

field name: name
field value: John Doe
field type: class java.lang.String
is primary: false

field name: email
field value: john.doe@example.com
field type: class java.lang.String
is primary: false

field name: created
field value: Wed Jul 25 17:10:05 BST 2018
field type: class java.util.Date
is primary: false
Comment
Article Tags:
Article Tags: