kacmak7
kacmak7

Reputation: 151

Java | variable value of attribute

I need to let a user of my program name an attribute of annotation, so I created fields in that class which could be managed by a user in main(), these fields should initialize a name attribute in the annotation of a getter, but Intellij IDEA tells that "Attribute value must be constant". Do you have any ideas how to do another way? There is the code:

public class Model {

    private String a;
    private String b;

    String nameA;

    public User(String a) {
        this.a = a;
    }

    public User(String a, String b) {
        this.a = a;
        this.b = b;
    }

    @XmlElement(name = nameA)
    public String getA() {
        return a;
    }

    public void setA(String a) {
        this.a = a;
    }

}

Upvotes: 3

Views: 243

Answers (1)

lexicore
lexicore

Reputation: 43661

You can only use constant expressions in annotations.

It appears you want to map your property using a dynamic element name. For this change the type of JAXBElement<String> and use the @XmlElementRef annotation instead of @XmlElement. You can then construct your value as:

new JAXBElement(new QName(nameA), String.class, "myValue");

Upvotes: 1

Related Questions