![]() |
VOOZH | about |
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
We are going to create three custom annotations with the goal of serializing an object into a JSON string. that is -
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 {
}Using the same fashion, we create our second annotation to mark the fields that we are going to include in the generated JSON :
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
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