Behrang Saeedzadeh
Behrang Saeedzadeh

Reputation: 47971

Is it possible to get the annotated element from an annotation instance?

If we have a class like this:

public class Foo {

  @MyAnnotation
  private String name;

}

And then have an instance of Foo:

Foo foo = new Foo();

Using reflection, we can get a Field instance representing name and from there using getAnnotation(MyAnnotation.class) we can get the instance of the annotation that is applied to the that field.

My question is, is it possible to get the annotated element (i.e. field, method, type, etc.) from an annotation?

For example:

MyAnnotation anno = ...;
anno.getField(); // returns the `Field` object representing the `name` field of a particular instance of `Foo`

Upvotes: 4

Views: 1492

Answers (1)

slipperyseal
slipperyseal

Reputation: 2778

No. :)

It appears to be a one way reference. I assume you want to pass the annotation to some other code which would then need to know what it was applied to? When you extract the annotations from the annotated element, you would store the field, method etc with the annotation at that time. Perhaps create a wrapper bean which contains the Annotation and the annotated element.

Or, if the original class is available, get all annotations all compare them for equality, returning the element when there is a match. Not preferable, but possible.

Upvotes: 2

Related Questions