Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create custom annotation in java?

I want to create custom annotation in java for DirtyChecking. Like I want to compare two string values using this annotation and after comparing it will return a boolean value.

For instance: I will put @DirtyCheck("newValue","oldValue") over properties.

Suppose I made an interface:

 public @interface DirtyCheck {
    String newValue();
    String oldValue();
 }

My Questions are:

  1. Where I make a class to create a method for comparison for two string values? I mean, how this annotation notifies that this method I have to call?
  2. How to retreive returning values of this method ?
like image 454
psisodia Avatar asked Sep 04 '12 09:09

psisodia


People also ask

Can we create our own annotations in Java?

To create your own Java Annotation you must use @interface Annotation_name, this will create a new Java Annotation for you. The @interface will describe the new annotation type declaration. After giving a name to your Annotation, you will need to create a block of statements inside which you may declare some variables.


3 Answers

First you need to mark if annotation is for class, field or method. Let's say it is for method: so you write this in your annotation definition:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DirtyCheck {
    String newValue();
    String oldValue();
}

Next you have to write let's say DirtyChecker class which will use reflection to check if method has annotation and do some job for example say if oldValue and newValue are equal:

final class DirtyChecker {

    public boolean process(Object instance) {
        Class<?> clazz = instance.getClass();
        for (Method m : clazz.getDeclaredMethods()) {
            if (m.isAnnotationPresent(DirtyCheck.class)) {
                DirtyCheck annotation = m.getAnnotation(DirtyCheck.class);
                String newVal = annotation.newValue();
                String oldVal = annotation.oldValue();
                return newVal.equals(oldVal);
            }
        }
        return false;
    }
}

Cheers, Michal

like image 155
Michal Avatar answered Oct 06 '22 01:10

Michal


To answer your second question: your annotation can't return a value. The class which processes your annotation can do something with your object. This is commonly used for logging for example. I'm not sure if using an annotation for checking if an object is dirty makes sense except you want to throw an exception in this case or inform some kind of DirtyHandler.

For your first question: you could really spent some effort in finding this yourself. There are enough information here on stackoverflow and the web.

like image 20
Kai Avatar answered Oct 05 '22 23:10

Kai


CustomAnnotation.java

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation {
     int studentAge() default 21;
     String studentName();
     String stuAddress();
     String stuStream() default "CS";
}

How to use the field of Annotation in Java?

TestCustomAnnotation.java

package annotations;
import java.lang.reflect.Method;
public class TestCustomAnnotation {
     public static void main(String[] args) {
           new TestCustomAnnotation().testAnnotation();
     }
     @CustomAnnotation(
                studentName="Rajesh",
                stuAddress="Mathura, India"
     )
     public void testAnnotation() {
           try {
                Class<? extends TestCustomAnnotation> cls = this.getClass();
                Method method = cls.getMethod("testAnnotation");

                CustomAnnotation myAnno = method.getAnnotation(CustomAnnotation.class);

                System.out.println("Name: "+myAnno.studentName());
                System.out.println("Address: "+myAnno.stuAddress());
                System.out.println("Age: "+myAnno.studentAge());
                System.out.println("Stream: "+myAnno.stuStream());

           } catch (NoSuchMethodException e) {
           }
     }
}
Output:
Name: Rajesh
Address: Mathura, India
Age: 21
Stream: CS

Reference

like image 42
Rajesh Dixit Avatar answered Oct 06 '22 00:10

Rajesh Dixit