24

I have a generated class that looks like below. I need to call setAmount() from a POJO, but I don't know what value to pass for the arg. It takes type JAXBElement, and I haven't found a way to instantiate that.

I have an ObjectFactory, but it only creates the class CardRequest.

Can anyone suggest a way?

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "amount",
})
@XmlRootElement(name = "card-request")
public class CardRequest {

    @XmlElementRef(name = "amount", namespace = "http://mycompany/services", type = JAXBElement.class)
    protected JAXBElement<String> amount;

    public JAXBElement<String> getAmount() {
        return amount;
    }

    public void setAmount(JAXBElement<String> value) {
        this.amount = ((JAXBElement<String> ) value);
    }
}
EdgeCase
  • 4,719
  • 16
  • 45
  • 73

1 Answers1

52

You can do the following:

JAXBElement<String> jaxbElement = 
    new JAXBElement(new QName("http://mycompany/services", "amount"), String.class, "Hello World");

There should also be a create method on the generated ObjectFactory class that will create this instance of JAXBElement with the appropriate info for you.

ObjectFactory objectFactory = new ObjectFactory();
JAXBElement<String> jaxbElement = objectFactory.createAmount("Hello World");

UPDATE

If the element definition is nested within your schema the name of the create method might be longer such as createCardRequestAmount().

bdoughan
  • 147,609
  • 23
  • 300
  • 400
  • 1
    Every example I've seen suggest that I should see the ObjectFactory create method. But I just don't see one for createAmount, just the CardRequest class itself. But your 1st solution worked perfectly! I'll be sure to accept when the time expires. – EdgeCase Oct 23 '13 at 17:32
  • @EdgeCase - If `amount` is an element that is very nested in the XML schema the create method may be called something longer. Can you search your `ObjectFactory` for create methods that contain `amount`? – bdoughan Oct 23 '13 at 17:33
  • 1
    Yep! Exactly as you describe. Found "createCardRequestAmount()" Thanks a million. – EdgeCase Oct 23 '13 at 17:37
  • 1
    What is the package name for ObjectFactory? I find 10 different ObjectFactory's when attempting to import. Not sure what to use. – randominstanceOfLivingThing Feb 24 '17 at 22:02
  • 1
    @randominstanceOfLivingThing There's an ObjectFactory for every package that was created by xjc, you need the ObjectFactory in the same package as the class you're trying to instantiate. – Ivo van der Veeken Mar 02 '17 at 17:06
  • 1
    @IvovanderVeeken, I figured it eventually. Thanks for pointing it though. Someone will benefit from this info for sure. – randominstanceOfLivingThing Mar 02 '17 at 18:05