0

I have the following bean:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "BankType", propOrder = {

})
public class BankType {

    @XmlElement(name = "Bank_Name")
    protected StringPropertyType bankName;
...

In my code I have a reference to the bankName instance variable. I need to know the value of the name property on @XmlElement.

I presumed that the annotation on instance variable can be retrieved from the parent class (BankType) by calling the getDeclaredFields().getDeclaredAnnotations(), see https://stackoverflow.com/a/4454783/1269572).

However I don't know how to get a reference to the BankType object where the object of the instance variable I have is. Any hint please?

Or do you know other magic how to get the annotation of an instance variable?

Thanks a lot!

------------------- UPDATE 1 -------------------

I don't know the parent class (here it's BankType) that's why I have to get it dynamically from the object of the instance variable somehow ...
I parsing a large XML and which contains lots of StringPropertyType in different classes.

Viktor
  • 1,325
  • 2
  • 19
  • 41
  • I’m not sure I understand. If you have an instance, you can get its class, hence annotations. The annotation will be the same for all instances. How to get a reference to a specific instance is up to you and your code. – Dave Newton Jul 15 '20 at 13:36
  • Hi Dave, thanks for the comment! If I get the class of the `bankName` instance variable then I will get the `StringPropertyType` and its annotation is not the `@XmlElement' but others (`@XmlAccessorType` and `@XmlType` like the `BankType` has). I can get the annotation of the instance variable if I have the class (`BankType`) where the instance variable is. I don't know the parent class (here it's `BankType`) that's why I have to get it dynamically somehow. – Viktor Jul 15 '20 at 13:45
  • @Viktor did you take a look at differences between `getDeclaredFields()` and `getFields()`? Same for the `getDeclaredAnnotations()` and `getAnnotations()`? The latter gathers inherited annotations. Using `declared` gathers only fields and annotations for class you operate on and ignoring the inheritance – Fenio Jul 15 '20 at 14:15
  • Hi Fenio, thanks! I tried with the `getAnnotations()` on the instance variable but still I got the 2 annotations on the class level (not the `@XmlElement`). – Viktor Jul 15 '20 at 14:25
  • 1
    Not all annotations are kept during runtime, e.g., `@Retention(RetentionPolicy.RUNTIME)` is required if the annotation def wants it to be available via reflection at runtime. So it depends at least partially on what `@XmlElement` you're using. – Dave Newton Jul 15 '20 at 14:36

0 Answers0