vendredi 11 mars 2016

Setting annotation value to fieldName

I'd like to set the default annotation value to fieldName. I think it would be similar to javax.persistence.Column or org.apache.camel.dataformat.bindy.annotation.DataField annotations. I looked at some questions that may be related Modify field annotation value dynamically , but I still don't understand how it's done.

So for example I have:

@Target(java.lang.annotation.ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String name() default "";
}

and I want to use it like this:

@MyAnnotation
String someField;

If I do something like this:

Field[] fields = MyClass.class.getDeclaredFields();
        for(Field field : fields){
            if (field.isAnnotationPresent(Column.class)){
                Column annotation = field.getAnnotation(Column.class);
                System.out.println(field.getName());
                System.out.println(annotation.name());
            }
        }

At this point the value for name is not set to fieldName.

So my question is:

  1. Is the field actually ever set or the value is only used if specified and if not the name is returned through field reflection and never set on the annotation.
  2. If 1) is true , At what point and how the name field of the annotation is set to the desired value.
  3. How can I replicate this annotation in my own custom annotation (I guess it's mainly the same as the how from 2 above).

Please explain or refer me to some information regarding this.





Aucun commentaire:

Enregistrer un commentaire