Java Annotations-Business logic implementation


I want to write my own annotations, as there are several ideas, but I can't figure out how to do it. It seems easy, but the question is: how to attach business logic to the annotation? What can I do with the data that I received in the annotation. example: @Annotation(SomeValue.VALUE). And how do I take this into account and do some business logic with it? For example, to put it in a method from another library, scroll through it and return the values..

Author: raviga, 2017-02-07

1 answers

To use your own annotation, you need to:

  1. Implement an annotation (public @interface MyAnnotationExample with the annotation type ElementType - for example: class/method/constructor/field, etc.).
  2. Use this annotation MyAnnotationExample in your code (according to the ElementType type of the annotation MyAnnotationExample), i.e. add an annotation to a class/method/field/etc.
  3. Implement the handler for this annotation via reflection.

Example #1. Annotation on the class and reading the class annotation through reflection.

Creating an annotation MyAnnotationExampleForClass:

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

@Target(value = ElementType.TYPE) //указание что данная аннотация вешается на класс
@Retention(value = RetentionPolicy.RUNTIME) //аннотация доступна в процессе работы модуля
public @interface MyAnnotationExampleForClass {

    String name() default "default name"; //в name() мы будем хранить значения аннотации
}

Creating the MyClassExample class using the {[9] annotation]}:

@MyAnnotationExampleForClass(name = "this is my annotation value!!!")
public class MyClassExample {
...
}

Creating a class MyAnnotationProcessorExample for getting annotation values:

class MyAnnotationProcessorExample {
        MyClassExample myClass = new MyClassExample();
        //получаем нашу аннотацию из нашего объекта
        MyAnnotationExampleForClass a = myClass.getClass().getAnnotation(MyAnnotationExampleForClass.class);
    System.out.println("выводим значение аннотации = " + a.name());
    System.out.println("печатаем тип аннотации со значением = " + a.toString());
    }

Example #2. Annotation on the class method and reading the method annotation through reflection. Adding another annotation MyAnnotationExampleForMethod for the method:

@Target(value = ElementType.METHOD)
@Retention(value = RetentionPolicy.RUNTIME)
public @interface MyAnnotationExampleForMethod {

    String name() default "default name 2";
}

Let's add MyClassExample to our class (from example #1) new method runForest():

@MyAnnotationExampleForClass(name = "this is my annotation value!!!")
public class MyClassExample {

    @MyAnnotationExampleForMethod(name = "this is my method-annotation value")
    public void runForest() { System.out.println("Our Forest run very good!"); }
}

Creating a class MyAnnotationProcessorExample2 for getting annotation values:

class MyAnnotationProcessorExample2 {
        MyClassExample myClass = new MyClassExample();

        //получаем наш метод из нашего объекта
        Method m = tm.getClass().getMethod("runForest");

        //получаем аннотацию из нашего метода
        MyAnnotationExampleForMethod a = m.getAnnotation(TimeAnnotationMethod.class);

    System.out.println("выводим значение аннотации = " + a.name());
    System.out.println("печатаем тип аннотации со значением = " + a.toString());
    }

Now you can use these handler classes MyAnnotationProcessorExample and MyAnnotationProcessorExample2 in the right places for processing business logic. I gave the most primitive examples, just for general understanding. For more complete implementations, you need to understand the concept of java reflection.

I also recommend looking at the topics:

  1. When to apply reflection in practice, annotations?
  2. Why create your own annotations?
  3. Annotation in Java EE
 8
Author: Mikhail Grebenev, 2017-04-13 12:53:29