Java 为 JAXBElement<String> 设置值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19548374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set a Value for JAXBElement<String>
提问by EdgeCase
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.
我有一个如下所示的生成类。我需要从 POJO 调用 setAmount(),但我不知道要为 arg 传递什么值。它采用 JAXBElement 类型,我还没有找到实例化它的方法。
I have an ObjectFactory, but it only creates the class CardRequest.
我有一个 ObjectFactory,但它只创建类 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);
}
}
采纳答案by bdoughan
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
类上还应该有一个 create 方法,它将JAXBElement
使用适当的信息为您创建此实例。
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()
.
如果元素定义嵌套在您的架构中,则创建方法的名称可能会更长,例如createCardRequestAmount()
.