I have to initialize an element of type JAXBElement <String>, I have tried as follows:
JAXBElement<String> element = new JAXBElement<>(new QName("http://tempuri.org/", "FieldName"), String.class, "FieldData");
But I am not sure if it is the correct way. Can someone confirm if there is another easier way?
What you posted is the simplest way of initializing a
JAXBElementelement that I know of - a correct one.The two constructors are:
JAXBElement(QName name, Class<T> declaredType, Class scope, T value)and (the simplest one, the one you used)
JAXBElement(QName name, Class<T> declaredType, T value)Also, keep in mind that if by Simple you mean, you don't need to initialize the object with the scope (3rd argument of the first constructor), then your code should be fine.
Edit:
The only questionable thing I see is the
"FieldName"(2nd argument provided to theQNameconstructor) - I'm not what it represents for you, but this should be the local part of theQName. For more info about this seepublic QName(String namespaceURI, String localPart)