users@jaxb.java.net

Use Enum Member Field as value in serializing?

From: Pinch, Marnee <Marnee.Pinch_at_Pearson.com>
Date: Thu, 16 Jul 2009 16:26:23 -0500

I have an enumeration where each member has an 'int id' field. I want
to use this field to identify the member during marshalling and
unmarshalling, not the name of the member itself.

 

One way to do it is to add @XmlEnumValue with the String representation
of the id:

 

public enum MyEnum {
 
    @XmlEnumValue("1")
    CONSTANT1(1, "constant1"),
 
    @XmlEnumValue("2")
    CONSTANT2(2, "constant2"),
 
...
 
    MyEnum (int id, String name) {
        this.id = id;
        this.name = name;
    }
}
 
public class MyClass {
 
    @XmlAttribute(name="id")
    MyEnum someEnum;
}
 
So, the desired output is:
 
<MyClass id="1"/>
 
This works, but we have a lot of members and don't want to have to
annotate each member.
 
There is a second way which doesn't require annotating the enum members
at all. This is the way I'm currently doing it. I use a private getter
and setter in the class that references the enum, as follows:
 
 
public class MyClass {
 
    private final SomeType type;
 
 
    @XmlAttribute(name="id")
 
    private int getTypeId() {
        return type.getID();
    }
 
        private void setTypeId(int typeId) {
               try {
                       final Field typeField =
getClass().getDeclaredField("type");
                       typeField.setAccessible(true);
                       typeField.set(this, SomeType.fromID(typeId));
               }
               catch (NoSuchFieldException ex) {
                       throw new RuntimeException(ex);
               }
               catch (IllegalAccessException ex) {
                       throw new RuntimeException(ex);
               }
        }
}
 
We need to use reflection to set the type field since it is final and we
want it to stay that way.
 

Both methods work.

 

However, I am wondering if there might be an even easier way to indicate
that the 'id' field in the enum member is to be used to identify the
enum in the XML?

 

 

Thanks,

Marnee