java 为什么 JAXB 不允许对从同一个成员变量中提取的 getter 进行注释?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4452191/
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
Why doesn't JAXB allow annotations on getters that all pull from the same member variable?
提问by Bernard Igiri
Why does example A work, while example B throws a "JAXB annotation is placed on a method that is not a JAXB property" exception?
为什么示例 A 可以工作,而示例 B 会抛出“JAXB 注释放置在不是 JAXB 属性的方法上”异常?
I'm using JAX-WS with Spring MVC.
我在 Spring MVC 中使用 JAX-WS。
Example A
示例 A
package com.casanosa2.permissions;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.PROPERTY)
@XmlType(name = "FooXMLMapper")
public class FooXMLMapper implements IFoo {
@XmlElement
private final boolean propA;
@XmlElement
private final boolean propB;
public FooMapper(IFoo foo) {
propA = foo.getPropA()
propB = foo.getPropB()
}
public FooMapper() {
propA = false;
propB = false;
}
@Override
public boolean getPropA() {
return propA;
}
@Override
public boolean getPropB() {
return propB;
}
}
Example B
示例 B
@XmlAccessorType(XmlAccessType.PROPERTY)
@XmlType(name = "FooXMLMapper")
public class FooXMLMapper {
private final IFoo foo;
public FooMapper() {
foo = new IFoo() {
@Override
public boolean getPropA() {
return false;
}
@Override
public boolean getPropB() {
return false;
}
};
}
public FooXMLMapper(IFoo foo) {
this.foo = foo;
}
@XmlElement
public boolean getPropA() {
return foo.getPropA();
}
@XmlElement
public boolean getPropB() {
return foo.getPropB();
}
}
采纳答案by Chris Kessel
I believe the accessors are ignored if it's looking directly at the instance variables and in your example B there are no actual instance variables of the right name. You have to tell it explicitly to use @XmlAccessorType(XmlAccessType.NONE) on the class and @XmlElement and @XmlAttribute on the get/set methods. At least, that's what I ended up doing with my JAXB mapping.
我相信访问器会被忽略,如果它直接查看实例变量,并且在您的示例 B 中没有正确名称的实际实例变量。您必须明确告诉它在类上使用 @XmlAccessorType(XmlAccessType.NONE) 并在 get/set 方法上使用 @XmlElement 和 @XmlAttribute。至少,这就是我最终使用 JAXB 映射所做的。
回答by bdoughan
I haven't tried your code yet, but it's example A that looks wrong, not B. In example A you have specified the property accessors (get/set methods) but you have annotated the class fields instead (instance variables).
我还没有尝试过你的代码,但它的示例 A 看起来有问题,而不是 B。在示例 A 中,您已经指定了属性访问器(get/set 方法),但您已经注释了类字段(实例变量)。
回答by Daniel Kulp
I believe for it to be a proper JAXB property, you would need setters for them as well as getters. (you would likely need a default constructor as well).
我相信它是一个合适的 JAXB 属性,你需要它们的 setter 和 getter。(您可能还需要一个默认构造函数)。