我有一些旧代码(pre Java 1.5),它使用类来实现类型安全枚举,如:
public class MyTypeSafeEnum implements java.io.Serializable {
private final int value;
private MyTypeSafeEnum(int value) {
this.value = value
}
public static final MyTypeSafeEnum FIRST_VALUE = new MyTypeSafeEnum(0)
public static final MyTypeSafeEnum SECOND_VALUE = new MyTypeSafeEnum(1)
public static final MyTypeSafeEnum THIRD_VALUE = new MyTypeSafeEnum(2)
public static fromInt(int value) {
//Builds a MyTypeSafeEnum from the value, implementation omitted
return theMyTypeSafeEnum;
}
public int getValue() {
return this.value;
}
}
我想在JAX-WS操作中使用这些枚举类作为参数,但在生成的WSDL中,类型的定义是空的:
<xs:complexType name="myTypeSafeEnum">
<xs:sequence/>
</xs:complexType>
我想我应该使用XmlAdapter,所以我创建了以下类:
public class MyTypeSafeEnumXmlAdapter extends XmlAdapter<MyTypeSafeEnum, Integer> {
@Override
public MyTypeSafeEnum marshal(Integer v) throws Exception {
return MyTypeSafeEnum.fromInt(v);
}
@Override
public Integer unmarshal(MyTypeSafeEnum e) throws Exception {
return e.getValue();
}
}
我在我的类中添加了@XmlJavaTypeAdapter(MyTypeSafeEnumXmlAdapter.class)
注释,但它对生成的WSDL没有任何影响。
如何在JAX-WS操作中将这些类用作参数?目前,重构代码以使用enum
类型是不可能的。
答案 0 :(得分:1)
您需要撤消MyTypeSafeEnumXmlAdapter中类型的顺序:
public class MyTypeSafeEnumXmlAdapter extends XmlAdapter<Integer, MyTypeSafeEnum> {
@Override
public Integer marshal(MyTypeSafeEnum v) throws Exception {
return v.getValue();
}
@Override
public MyTypeSafeEnum unmarshal(Integer v) throws Exception {
return MyTypeSafeEnum.fromInt(v);
}
}
那么如果你有这样一个类:
public class MyClass {
private MyTypeSafeEnum someVar;
@XmlJavaTypeAdapter(MyTypeSafeEnumXmlAdapter.class)
public MyTypeSafeEnum getSomeVar() {
return someVar;
}
}
它将生成如下的XML:
<xs:complexType name="myClass">
<xs:sequence>
<xs:element minOccurs="0" name="someVar" type="xs:int"/>
</xs:sequence>
</xs:complexType>
Web服务客户端将该字段视为整数。所以你必须确保它们不传入一个不映射到其中一个枚举实例的整数,或以某种方式处理它。