问题
I'm using the XSD listed below and a corresponding XML. Everything works well with dynamic MOXy but I haven't any idea how to access the enum type within java. Any suggestions? Thanks for help.
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema ...>
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="first-name" type="xs:string"/>
<xs:element name="last-name" type="xs:string"/>
<xs:element name="quadrant" type="myns:compass-direction"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:simpleType name="compass-direction">
<xs:restriction base="xs:string">
<xs:enumeration value="NORTH"/>
<xs:enumeration value="SOUTH"/>
<xs:enumeration value="EAST"/>
<xs:enumeration value="WEST"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>
//JAVA code
DynamicEntity person = (DynamicEntity) dynamicJAXBContext.createUnmarshaller().unmarshal(instanceDoc);
String firstName = person.get("firstName");
String lastName = person.get("lastName");
//until here it works well
//but now: how to get and set the value of the "quadrant"?
// following lines do not work
String quadrant=person.get("quadrant);
person.set("quadrant","NORTH");
回答1:
To use an enum value for a set() operation, you need to first look up the enum constant using DynamicJAXBContext.getEnumConstant(), and then use that for the set. For example:
Object NORTH = ctx.getEnumConstant("your.package.CompassDirection", "NORTH");
person.set("quadrant", NORTH);
To get the value, you are calling the correct code, but the value that comes back will not be a String, it will the actual enum value Object associated with that String. You should use:
Object quadrant = person.get("quadrant");
Hope this helps,
Rick
回答2:
If you have on value you can use the class to get all possible values.
protected static Enum[] getValues(Enum enumValue) {
return enumValue.getClass().getEnumConstants();
}
来源:https://stackoverflow.com/questions/5181374/eclipselink-dynamic-moxy-accessing-enum-values