1

If I have a parametrized annotation which is used on a field, can the object referenced by the field access the annotation parameter?

 @Retention(RetentionPolicy.RUNTIME)
  @Target(ElementType.FIELD)
  public @interface Classy {
      Class<?> klazz();
  }

usage:

class Bar{
    @Classy(klazz=Integer.class)
    Foo foo;
    ...
}

hypothetical access:

class  Foo{
  private Class<?> klazz = String.class;

  private void useAnnotationParameterIfAvailable(){
    klazz = what goes here?
  }
}

Thank you

kostja
  • 60,521
  • 48
  • 179
  • 224

3 Answers3

2

No - annotations are an attribute of the field, and the object can not iterate the fields currently referencing it (To efficiently find the fields, the JVM would have to maintain a dedicated lookup data structure, and update that upon every field assignment. This would be very expensive ...)

Of course, if the type of the object uniquely identifies the field, you could employ class path scanning to find all annotated fields of that type - but if the type identifies the class to use, putting the annotation on the type would be far easier :-)

meriton
  • 68,356
  • 14
  • 108
  • 175
-1

Use following method on the target feild.

java.lang.reflect.Field.getAnnotation(Class<T>)

A Sample Code

    try {
        Field field = this.getClass().getField("foo");
        Ignore annotation = field.getAnnotation(Classy.class);

        //do what ever with annotation
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
Vijay Shanker Dubey
  • 4,308
  • 6
  • 32
  • 49
  • Thanks Vijay, but I'm afraid you misunderstood the requirements - you are describing how I would access the annotation from the class containing the field, not from the filed instance itself. I.e. - the code cannot be used from inside `Foo` – kostja Jun 21 '12 at 10:36
-1

Foo.class.getAnnotation(Classy.class).klazz();

Note: may need some casting here and there, I don't have an IDE handy.

For more examples, see here:

http://tutorials.jenkov.com/java-reflection/annotations.html

and here:

Is it possible to read the value of a annotation in java?

Community
  • 1
  • 1
Istvan Devai
  • 3,962
  • 23
  • 21
  • Thanks Istvan - I'm afraid your approach cannot work as the `Foo` class itself is not annotated, only a field of type `Foo` in another class. `class.getAnnotation()` will always return `null`. – kostja Jun 21 '12 at 10:56
  • Yes, thought that the class itself is annotated, sorry. – Istvan Devai Jun 21 '12 at 11:34