Open In App

Customize Java Annotation with Examples

Improve
Improve
Like Article
Like
Save
Share
Report

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 :

Java




@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface GFGElement {
    public String key() default "";
}


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.

Java




@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Init {
}


Example

Java




package com.admfactory.annotation;
  
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
  
@Documented
@Target(ElementType.FIELD)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface DBField {
    String name();
  
    Class< ?> type();
  
    boolean isPrimaryKey() default false;
}


Usage:

Annotated Class

Java




package com.admfactory.annotation;
  
import java.util.Date;
  
public class User {
  
    @DBField(name = "id", isPrimaryKey = true, type = Long.class)
    private long id;
  
    @DBField(name = "name", type = String.class)
    private String name;
  
    @DBField(name = "email", type = String.class)
    private String email;
  
    @DBField(name = "created", type = Date.class)
    private Date created;
  
    public long getId() {
        return id;
    }
  
    public void setId(long id) {
        this.id = id;
    }
  
    public String getName() {
        return name;
    }
  
    public void setName(String name) {
        this.name = name;
    }
  
    public String getEmail() {
        return email;
    }
  
    public void setEmail(String email) {
        this.email = email;
    }
  
    public Date getCreated() {
        return created;
    }
  
    public void setCreated(Date created) {
        this.created = created;
    }
}


Runnable Code

Java




package com.admfactory.annotation;
  
import java.lang.reflect.Field;
import java.util.Date;
  
public class AnnotationExample {
  
    public static void main(String[] args) throws Exception {
        System.out.println("Java Custom Annotation Example");
        System.out.println();
  
        User usr = new User();
        usr.setEmail("john.doe@example.com");
        usr.setName("John Doe");
        usr.setId(112);
        usr.setCreated(new Date());
  
        for (Field field : usr.getClass().getDeclaredFields()) {
            DBField dbField = field.getAnnotation(DBField.class);
            System.out.println("field name: " + dbField.name());
  
            // changed the access to public
            field.setAccessible(true);
            Object value = field.get(usr);
            System.out.println("field value: " + value);
  
            System.out.println("field type: " + dbField.type());
            System.out.println("is primary: " + dbField.isPrimaryKey());
            System.out.println();
        }
    }
}


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


Last Updated : 12 Aug, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads