2

I have some old code (pre Java 1.5) that uses classes to implement type safe enums, something like:

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;
  }
 }

I want to use these enumeration classes as paremeters in a JAX-WS operation, but in the generated WSDL the definition for the type is empty:

<xs:complexType name="myTypeSafeEnum">
  <xs:sequence/>
</xs:complexType>

I figured I should use an XmlAdapter, so I created the following class:

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();
  }
}

I added the @XmlJavaTypeAdapter(MyTypeSafeEnumXmlAdapter.class) annotation to my class, but it had no effect in the generated WSDL.

How I can use these classes as parameters in a JAX-WS operation? At the moment, refactoring the code to use the enum type is out of question.

iruediger
  • 933
  • 6
  • 9

1 Answers1

1

You need to reverse the order of the types in your 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);
    }
}

So then if you have a class like this:

public class MyClass {
    private MyTypeSafeEnum someVar;

    @XmlJavaTypeAdapter(MyTypeSafeEnumXmlAdapter.class)
    public MyTypeSafeEnum getSomeVar() {
        return someVar;
    }
}

It will generate the XML like this:

<xs:complexType name="myClass">
    <xs:sequence>
        <xs:element minOccurs="0" name="someVar" type="xs:int"/>
    </xs:sequence>
</xs:complexType>

The web service clients will see that field as an integer. So you'll have to make sure they don't pass in an integer that doesn't map to one of the enum instances, or handle it somehow.

Jason Wheeler
  • 872
  • 1
  • 9
  • 23