Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java | variable value of attribute

Tags:

java

jaxb

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;
    }

}
like image 783
kacmak7 Avatar asked Jun 24 '26 08:06

kacmak7


1 Answers

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");
like image 193
lexicore Avatar answered Jun 25 '26 20:06

lexicore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!