Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding programmatic annotations to a Java class

Usage example:
I want to put on class fields a custom annotation @MyContainer and then add automatically on all such fields relevant Hibernate annotations (depending on field type and properties).
In additional I need to add JAXB XmlType annotation to the class and base the type name on the class name.
I would want additionally to add annotations to fields based on thier types, etc. All added annotations should be available at run time (So hibernate / JAXB can find them).
I'm aware of the following options:

  1. Pre-processing class source (bad option)
  2. Processing during compilation with javax.annotation.processing APIs
  3. Post compilation manipulation with tools such as Java Assist
  4. Manipulation during class loading with java.lang.instrument APIs
  5. Doing it with AspectJ (not powerful enough)

My primary goals are:

  1. Keep sync between class and source for debugging
  2. Support working from both Maven and IDE (Eclipse / Intellij)

I'll appreciate if people who already done such things can recommend the best approach for such a task (and perhaps potential pitfalls).

like image 672
Avner Levy Avatar asked Jul 22 '12 06:07

Avner Levy


1 Answers

Here is a code example for defining custom annotation. This @TesterInfo is applied on class level, store the tester details. This shows the different use of return types – enum, array and string.

package com.mkyong.test.core;

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

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE) //on class level
public @interface TesterInfo {

    public enum Priority {
       LOW, MEDIUM, HIGH
    }

    Priority priority() default Priority.MEDIUM;

    String[] tags() default "";

    String createdBy() default "Mkyong";

    String lastModified() default "03/01/2014";

}
like image 162
Dev707 Avatar answered Oct 26 '22 01:10

Dev707