vendredi 25 janvier 2019

Access to annotation values through instanciated objects in Java

I have a CustomValue class like this :

public class CustomValue<T> {
   T value;
}

And a bean object that implements many fields of CustomValue class with an annotation @Settings :

public class Bean {
   @Settings(precision = 3600.0f)
   CustomValue<Timestamp> birthdate;

   @Settings(precision = 0.1f)
   CustomValue<Float> tall;

   @Settings(precision = 1.0f)
   CustomValue<Float> age;

   @Settings(precision = 100.0f)
   CustomValue<Float> numberOfHairOnTheHead;
}

Here is the @Settings annoation :

@Target({ElementType.FIELD, ElementType.TYPE})
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface Seetings {
    float precision() default 1.0f;
} 

When i instanciate a Bean object, i would like to access to the @Settings informations through instanciated value, without using Field object.

The following is false and do not work, but this is what i would like to manage to do.

Bean o = new Bean();

System.out.println(o.birthdate.precision); // 3600.0f

System.out.println(o.tall.precision); // 0.1f

System.out.println(o.age.precision); // 1.0f

System.out.println(o.numberOfHairOnTheHead.precision); // 100.0f

Is it possible to do it this way ?

It seems that i should use another way than Annotations to apply constant values to specific fields variables of a class ?





Aucun commentaire:

Enregistrer un commentaire