Enum serialization

Has anyone ever tried to use the RemoteClass metatag for
serializing between Java and AS3 implementations of an enum? The
guide gives a good example of how to fake an enum in AS3, but I'm
assuming I would have to develop custom serialization for enums.
True?

Here's the best way to serialize an enum I can think of.
Here's an example of an AS3 enum:
public class MyEnum {
public static var APPLES:MyEnum = new MyEnum("APPLES");
public static var ORANGES:MyEnum = new MyEnum("ORANGES");
private var name:String;
public function MyEnum(str:String) {
name = str;
public function toString() {
return name;
Unfortunately, implementing the IExternalizable interface for
the enum class is pretty much useless. By the time readExternal()
is called on your AS3 enum object, it has already been created and
you have no hope of limiting the instances of your enum class to
those defined as static members. AS3 serialization does not allow a
class to define how it is created, only how it populates it's own
fields after it has been created, which happens mysteriously at the
top of the call stack for the main thead.
Without any way of controlling the creation of the enum
object such as registering a Factory or implementing readResolve()
as in Java, you have to implement IExternalizable in an enclosing
class such as:
public class MyEnclosure implements IExternalizable {
var myEnum:MyEnum;
public function readExternal(input:IDataInput):void {
myEnum = MyEnum[input.readUTF()];
public function writeExternal(output:IDataOutput):void {
output.writeUTF(myEnum.toString());
Of course, the Java implementation must have an analogous
implementation for IExternalizable. If your Java class does not
implement IExternalizable, your AS3 readExternal() method will not
be called, even though the standard Java enum serialization format
is just fine for our purposes.
Worse, if your enum is a member of multiple enclosing value
objects, you have to externalize the serialization for all of these
classes.
Even worse, the default AS3 deserialization (unfortunately)
does
something for a Java enum when the IExternalizable interface
is not implemented. It creates a new instance of your enum, and
apparently throws away the "name" that is included in the Java
serialization stream.
Why?? At the Flex framework level, implementing serialization
using a scheme I have defined here would be trivial. However, if
that gets implmented now it would break backward compatibility. The
only options for framework support of deserialization of enums
would be to formally introduce enums into the language (not
happening), or to create a [RemoteEnum] metatag that would enforce
the semantics I describe, or to offer something analogous to the
Java readResolve() method.
The upshot is that every class that aggregates an enum, must
implement IExternalizable, instead of the more intuitive approach
of implementing IExternalizable for the enum class itself.
For completeness, here is the Java implementation of the
enclosing class:
public class MyEnclosure implements IExternalizable {
private MyEnum myEnum;
public void writeExternal(ObjectOutput output) throws
IOException {
output.writeUTF(myEnum.name());
public void readExternal(ObjectInput input) throws
IOException, ClassNotFoundException {
myEnum = Enum.valueOf(MyEnum.class, input.readUTF());

Similar Messages

  • Java 5 Enums serialization with XMLEncoder...

    Hello,
    I'd like to know why a bean attribute whose type is a Java 5 enum is
    not saved when using XMLEncoder. This field is in fact ignored...
    Anybody knows how to persist such fields using standard JDK (I mean
    no third party library) ?
    public enum TestBeanEnum {
        R160x100,
        R320x200,
        R640x480,
        R800x600,
        R1024x768,
        R1280x1024,
        R1600x1200;
    public class Setup {
        private TestBeanEnum a0;
        private boolean a1;
        public Setup() {
        public boolean isA1() {
            return a1;
        public void setA1(boolean a1) {
            this.a1 = a1;
        public TestBeanEnum getA0() {
            return a0;
        public void setA0(TestBeanEnum a0) {
            this.a0 = a0;
        private static void save(Setup setup, File file) throws IOException {
            FileOutputStream out = new FileOutputStream(file);
            XMLEncoder encoder = new XMLEncoder(out);
            encoder.writeObject(setup);
            encoder.close();
            out.close();           
    ...Only the attribute a0 is not saved all over, even relatively complex data
    types are automatically persisted.
    I also find a strange behavior, the keyword "transient" seems to be ignored
    by the XMLEncoder and a transient field is made persistent !!!
    Did I miss something ? Is this strange behavior a bug ?
    Thanks for all,
    David Crosson.

    looks like a bug to me
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5015403

  • Problem with DeSerilization

    Hi Guys
    I am stuck in a problem for which I need your help.
    I have used Enum.java class and provided a typemapping in the wsdd as follows
    <typeMapping
    xmlns:ns="http://localhost/hth/services/Equipment?wsdl"
    qname="ns:Enum"
    type="java:com.march.hth.client.Enum"
    serializer="org.apache.axis.encoding.ser.BeanSerializerFactory"
    deserializer="org.apache.axis.encoding.ser.BeanDeserializerFactory"
    encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
    />
    The code for Enum.java class is not being generated in the WSDL file.
    When I run my client which I have written to access this webservice method.i get the following exception.
    - Exception:
    org.xml.sax.SAXException: No deserializer for {http://localhost/hth/services/Equipment?wsdl}Enum
    I tried to replace theBeanSerializerFactory, BeanDeSerializerFactory with EnumSerializerFactory & EnumDeSerializerFactory but still the error persists.
    I have provided the typemapping that is needed but still I am getting this error.
    I am not able to figure out whats wrong here. The same thing works in other session beans where the Enum class is being generated in the WSDL from the wsdd file.
    Please let me know what should be done in this case.
    Thanks & Regards
    Vikram K

    hi guys
    any takers for my problem which is pending since yesterday.
    any help will be greatly appreciated.
    Regards
    Vikeng

  • Serialization issue with Java 5 enum

    Hi,
    In one of my DTO class, i have used an enum as an instance variable. But I am getting a serialization error during RMI call.
    Caused by: org.omg.CORBA.MARSHAL: Mismatched serialization UIDs : Source (RepId RMI:com.nokia.oss.interfaces.usermanagement.dtos.UMStatusDTO:1191975053A2D5C1:0000000000000001) = 0000000000000001 whereas Target (RepId RMI:com.nokia.oss.interfaces.usermanagement.dtos.UMStatusDTO:7F5FECD5609C39F7:6318A841C6045391) = 6318A841C6045391  vmcid: IBM  minor code: 8B1  completed: No
         at com.ibm.rmi.io.IIOPInputStream.simpleReadObject(IIOPInputStream.java:467)
         at com.ibm.rmi.io.ValueHandlerImpl.readValue(ValueHandlerImpl.java:209)
         at com.ibm.rmi.iiop.CDRInputStream.read_value(CDRInputStream.java:1638)
         at com.ibm.rmi.util.ProxyUtil.copyObject(ProxyUtil.java:450)
         at com.ibm.rmi.util.ProxyUtil.invokeWithClassLoaders(ProxyUtil.java:754)
         at com.ibm.CORBA.iiop.ClientDelegate.invoke(ClientDelegate.java:1161)
         at $Proxy322.createUserProfiles(Unknown Source)
         at com.nokia.oss.interfaces.usermanagement.ejb.useradministration._UMUserAdministration_Stub.createUserProfiles(Unknown Source)
         at com.nokia.oss.tmf615.uamadapters.connectors.UMAPI$2$1.run(UMAPI.java:187)
         at com.nokia.oss.tmf615.uamadapters.connectors.UMAPI$2$1.run(UMAPI.java:186)
         at java.security.AccessController.doPrivileged(AccessController.java:246)
         at com.nokia.oss.tmf615.uamadapters.connectors.UMAPI$2.run(UMAPI.java:184)
         at com.nokia.oss.tmf615.uamadapters.connectors.UMAPI$2.run(UMAPI.java:182)
         at java.security.AccessController.doPrivileged(AccessController.java:279)
         at javax.security.auth.Subject.doAs(Subject.java:573)
         at com.ibm.websphere.security.auth.WSSubject.doAs(WSSubject.java:168)
         at com.nokia.oss.tmf615.uamadapters.connectors.UMAPI.createUserProfiles(UMAPI.java:179)
         at com.nokia.oss.tmf615.uamadapters.operations.impl.UserManagerImpl.createUserProfile(UserManagerImpl.java:148)
         at com.nokia.oss.tmf615.uamadapters.operations.impl.UserManagerImpl.createUser(UserManagerImpl.java:81)
         at com.nokia.oss.tmf615.requesthandler.factory.ManageUAMImpl.createUser(ManageUAMImpl.java:103)
         at com.nokia.oss.tmf615.requesthandler.operations.RequestProcessor.addUserRequest(RequestProcessor.java:342)
         at urn.oasis.names.tc.SPML._2._0.wsdl.SPMLRequestPortTypeImpl.spmlAddRequest(SPMLRequestPortTypeImpl.java:1028)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:79)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
         at java.lang.reflect.Method.invoke(Method.java:618)
         at com.sun.xml.ws.api.server.InstanceResolver$1.invoke(InstanceResolver.java:246)
         at com.sun.xml.ws.server.InvokerTube$2.invoke(InvokerTube.java:146)
         at com.sun.xml.ws.server.sei.EndpointMethodHandler.invoke(EndpointMethodHandler.java:257)
         at com.sun.xml.ws.server.sei.SEIInvokerTube.processRequest(SEIInvokerTube.java:93)
         at com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:595)
         at com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:554)
         at com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:539)
         at com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:436)
         at com.sun.xml.ws.server.WSEndpointImpl$2.process(WSEndpointImpl.java:243)
         at com.sun.xml.ws.transport.http.HttpAdapter$HttpToolkit.handle(HttpAdapter.java:444)
         at com.sun.xml.ws.transport.http.HttpAdapter.handle(HttpAdapter.java:244)
         at com.sun.xml.ws.transport.http.servlet.ServletAdapter.handle(ServletAdapter.java:135)
         at com.sun.xml.ws.transport.http.servlet.WSServletDelegate.doGet(WSServletDelegate.java:129)
         at com.sun.xml.ws.transport.http.servlet.WSServletDelegate.doPost(WSServletDelegate.java:160)
         at com.sun.xml.ws.transport.http.servlet.WSServlet.doPost(WSServlet.java:75)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:763)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
         at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1146)
         at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:593)
         at com.ibm.ws.wswebcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:533)
         at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3548)
         at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:269)
         at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:818)
         at com.ibm.ws.wswebcontainer.WebContainer.handleRequest(WebContainer.java:1478)
         at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:125)
         at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:458)
         at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewInformation(HttpInboundLink.java:387)
         at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:267)
         at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
         at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
         at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165)
         at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
         at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
         at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:136)
         at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:196)
         at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:751)
         at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:881)
         at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1497)My environment has WebSphere Application Server 6.1.
    Earlier, I had used serialVersionUID generated by Eclipse, but to debug I changed it to 1L. But still I am facing the same issue. Any help in solving this issue is greatly appreciated.
    Thanks.

    Caused by: org.omg.CORBA.MARSHAL: Mismatched serialization UIDs : Source (RepId RMI:com.nokia.oss.interfaces.usermanagement.dtos.UMStatusDTO:1191975053A2D5C1:0000000000000001) = 0000000000000001 whereas Target (RepId RMI:com.nokia.oss.interfaces.usermanagement.dtos.UMStatusDTO:7F5FECD5609C39F7:6318A841C6045391) = 6318A841C6045391  vmcid: IBM  minor code: 8B1  completed: NoEarlier, I had used serialVersionUID generated by Eclipse, but to debug I changed it to 1L.Why? To debug what? How would that help? This is exactly the problem that the exception message (above) is reporting. Change it back to 6318A841C6045391L.

  • Serialization problems of enums

    Hello all,
    I try to call an EJB that contains a Java 5 - Enum value in the response object (com.customer.project.mad.exceptions.MadMessageID). But I only get an IOException with the messages that the serialization ID does match.
    According to the Java 5 Serialization Spec the serialVersionID of an enum should always be 0, but this doesn't seem to be true in all cases?!
    I also tried using the same JVM on server/client (Sun VM 1.50_4) with BEA WebLogic 9.2 on Windows XP.
    Any ideas?
    Caused by: java.io.IOException: Mismatched serialization UIDs : Source (Rep.
    IDRMI:com.customer.project.mad.exceptions.MadMessageID:3762E1FD1A6B1BE5:AF0788D2139910A8)
    = AF0788D2139910A8 whereas Target (Rep. ID
    RMI:com.customer.project.mad.exceptions.MadMessageID:64D47C1D01980B5E:0000000000000000)
    = 0000000000000000
            at
    com.sun.corba.se.impl.util.RepositoryId.useFullValueDescription(RepositoryId.java:577)
            at
    com.sun.corba.se.impl.io.ValueHandlerImpl.useFullValueDescription(ValueHandlerImpl.java:388)
            at
    com.sun.corba.se.impl.io.IIOPInputStream.simpleReadObject(IIOPInputStream.java:397)
            at
    com.sun.corba.se.impl.io.ValueHandlerImpl.readValueInternal(ValueHandlerImpl.java:327)
            at
    com.sun.corba.se.impl.io.ValueHandlerImpl.readValue(ValueHandlerImpl.java:293)
            at
    com.sun.corba.se.impl.encoding.CDRInputStream_1_0.read_value(CDRInputStream_1_0.java:1034)--
    Edited by eric.hambuch at 02/11/2007 11:10 AM

    Eric Hambuch <> writes:
    The RMI-IIOP spec for Enums is undefined at present, the JavaIDL rtf
    is voting on it currently. You would have to raise an enhancement
    request to get this tested and fixed in WLS.
    andy
    Hello all,
    I try to call an EJB that contains a Java 5 - Enum value in the response object (com.schenker.project.mad.exceptions.MadMessageID). But I only get an IOException with the messages that the serialization ID does match.
    According to the Java 5 Serialization Spec the serialVersionID of an enum should always be 0, but this doesn't seem to be true in all cases?!
    I also tried using the same JVM on server/client (Sun VM 1.50_4) with BEA WebLogic 9.2 on Windows XP.
    Any ideas?
    Caused by: java.io.IOException: Mismatched serialization UIDs : Source (Rep.
    IDRMI:com.schenker.project.mad.exceptions.MadMessageID:3762E1FD1A6B1BE5:AF0788D2139910A8)
    = AF0788D2139910A8 whereas Target (Rep. ID
    RMI:com.schenker.project.mad.exceptions.MadMessageID:64D47C1D01980B5E:0000000000000000)
    = 0000000000000000
    at
    com.sun.corba.se.impl.util.RepositoryId.useFullValueDescription(RepositoryId.java:577)
    at
    com.sun.corba.se.impl.io.ValueHandlerImpl.useFullValueDescription(ValueHandlerImpl.java:388)
    at
    com.sun.corba.se.impl.io.IIOPInputStream.simpleReadObject(IIOPInputStream.java:397)
    at
    com.sun.corba.se.impl.io.ValueHandlerImpl.readValueInternal(ValueHandlerImpl.java:327)
    at
    com.sun.corba.se.impl.io.ValueHandlerImpl.readValue(ValueHandlerImpl.java:293)
    at
    com.sun.corba.se.impl.encoding.CDRInputStream_1_0.read_value(CDRInputStream_1_0.java:1034)

  • Are enums in 1.5 Serializable?

    Hi, just wondering if I defined an enum with a couple of methods, is this enum automatically Serializable, i.e. does it already implement Seriablizable? e.g. is the enum below automatically serializable or must i have to explicitly implement it:
    public enum Ariithmetic {
    ADD, SUBTRACT, MULTIPLY, DIVIDE;
    public static Arithmetic getType( String type )
    thanks in advance!
    -los

    public abstract class Enum<E extends Enum<E>>
    extends Object
    implements Comparable<E>, Serializable

  • Type Safe enum with Serializable issue

    The following code is copied from www.javapractices.com
    public final class SimpleSuit {
      public static final SimpleSuit CLUBS = new SimpleSuit ("Clubs");
      public static final SimpleSuit DIAMONDS = new SimpleSuit ("Diamonds");
      public static final SimpleSuit HEARTS = new SimpleSuit ("Hearts");
      public static final SimpleSuit SPADES = new SimpleSuit ("Spades");
      public String toString() {
        return fName;
      private final String fName;
      private SimpleSuit(String aName) {
        fName = aName;
    }It is known to be typesafe and able to perform object equality.
    Eg:
    SimpleSuit s = SimpleSuit.SPADES;
    if (s == SimpleSuit.SPASES)
    ..Thus, it is simple and fast enough by object equality comparison.
    But if I implement SimpleSuit with java.io.Serializable and send it over the network, of course that would become a totally new objects, therefore I can't usr object equality anymore. Any solution to make it work over Serialization?
    Thanks,
    Jax

    A serializable class may provide a 'readResolve' method. This is used to "designate a replacement when an instance of it is read".
    A common approach with enums is to provide a unique identifier (e.g, a string name, or integer id). The enum class can then provide a readResolve method which determines the correct replacement instance based on this id.
    An example of this is also available on the javapractices site you mentioned:
    http://www.javapractices.com/Topic1.cjp

  • What's the deal with enums?

    Hello,
    I'm trying to familiarise myself with the new Java features that project Tiger (Java 1.5) will introduce. I come from a C++ programming background. I very briefly studied enums whilst I learned C++ and never used them in my programs, so I was, quite frankly, relieved when I learned that Java didn't support them.
    But now it does.
    I'm wondering, from a software design and engineering perspective, what benefit enums will add to the Java language and software engineering in general. I have read some pleas and arguments for enums. As I understand those arguments, proponents feel that minor ledgibility improvements to switch statements (which some OO programmers don't use on the basis that it weakens the object-orientedness through its goto-esque break statements) necessitate the addition of a whole other structure.
    Out of curiosity, wouldn't it be more advantageous for Sun to put their efforts into supporting constant strings in switches in addition to primitive data types if people are so concerned with clarity?
    I fail to understand what enums will do that constant string arrays or constant values cannot. I would like to think that Sun wouldn't add C++ features unless if there was a reason to do so, so I believe that there are good reasons to introduce this feature.
    Please help clarify this confusion.
    Thank you!

    Comments on the previous posting inline. Note: I'll go off on a few tangents, but try to always return to the issue of enums. The fact that I go off on tangents (related initially to an enum type example) should show that enums help eliminate numerous problems.
    Fair enough, but wouldn't this accomplish the same thing in
    a slightly wordier wayPretty much. But you still have the validation code in there yourself:
    currentDirection = ( direction > 0 && direction < 5 ? direction : 0 );People can still accidentally enter an invalid value, and it won't get caught by the compiler. So, I could call set(Compass.WEST) and hope/expect that is equivalent to set(Direction.LEFT). This will only occur if both Compass.WEST and Direction.LEFT are the same int value. If they are not, then we are in trouble. Worse, still if Compass.WEST and Direction.RIGHT are the same value, the code will compile, and run without any illegal value flagging, but our traveller will go off in the wrong direction.
    Error handling tangent: Given the implementation, the error handling is not performed in set, rather the illegal value is captured as a zero, which must be dealt with at a later time - say in a switch statement that calls get. This is not a good idea - it increases the "distance" between the error occuring (bad call to set) and the error being detected (if xInt != 0). The larger the distance, the harder debugging is. If you throw an exception in set the bug is immediately flagged. With enums, none of this should be necessary.
    Implementation tangent: set, get and currentDirection are static. This is not a good idea - it only allows one direction. If you have multiple travellers, each would have a Direction object, but (sticking with constants) UP, etc. would still be static.
    I keep the switch statement in my enum workaround, but I believe that
    the second reply suggested that enum could altogether eliminate the
    use for switch statements. How exactly would it do that?enum in its simplest form would not remove switch. However, using an extension of the type-safe enum idiom (i.e. the current Java approach to enums), you can embed direction specific logic in each of the "enum" members. If I understand the enum-spec correcly, this will also be possible with the Java 1.5 enum language facility.
    So, for an example, sticking with the domain: Consider a class Location, with x and y elements, and a Direction. The non-OO, non-enum approach would be as follows:
    class Location {
        int x,y;
        void move (final int direction) {
            switch (direction) {
                case UP:
                    --y;
                    break;
                case DOWN:
                    ++y;
                    break;
                case LEFT;
                    --x;
                    break;
                case RIGHT:
                    ++x;
                    break;
                default;
                    throw new RuntimeException("Invalid direction " + direction);
    class Direction {
        public static final int UP = 1;
        public static final int DOWN = 2;
        public static final int LEFT = 3;
        public static final int RIGHT = 4;
    }Note that I've deliberately been loose with my visibility. All logic is in Location, and Direction is dumb. If we go with a type safe-enum idiom, we get:
    class Location {
        int x,y;
        void move (final Direction direction) {
            if (direction == Direction.UP) {
                --y;
            } else if (direction == Direction.DOWN) {
                ++y;
            } else if (direction == Direction.LEFT) {
                --x;
            } else if (direction == Direction.RIGHT) {
                ++x;
            } else { // direction is null
                throw new NullPointerException("null direction");
    class Direction {
        public static final Direction UP = new Direction();
        public static final Direction DOWN = new Direction();
        public static final Direction LEFT = new Direction();
        public static final Direction RIGHT = new Direction();
        private Direction () {} // the ctor is private to limit instances
    }This code is a rewrite of the int approach, but is "type-safe". We've moved from switch to if as we can't switch on object references. Note: there is still error handling code, as you're not "null-safe" (I don't know what the Java 1.5 spec says about this)
    Little else has changed - the responsibilities are still the same. We can address this by going OO, which removes the if (formerly a switch) statement, but does couple the classes.
    class Location {
        int x,y;
        void move (final Direction direction) {
            direction.move(this);
    class Direction {
        private final int xOffset, yOffset;
        private Direction (final int xOffset, final int yOffset) {
            this.xOffset = xOffset;
            this.yOffset = yOffset;
        public static final Direction UP = new Direction(0,1);
        public static final Direction DOWN = new Direction(0,-1);
        public static final Direction LEFT = new Direction(-1,0);
        public static final Direction RIGHT = new Direction(1,0);
        void move(final Location location) {
            location.x += xOffset;
            location.y += yOffset;
    }This removes any conditional logic, embedding (constructor parameterised) logic within Direction. It also eliminates the "null-safe" check, as direction.move(this) will throw an NPE if a null is passed.
    Also, I've read some things saying that enum reduces 'boilerplate'
    code. What exactly does that and 'boilerplate' mean?The Direction class is an example of the type-safe enum approach currently used in Java. It has been enhanced with logic for movement. Even if I dropped this logic, there is still functionality worth adding to the Direction class - a toString method that returns one of "UP", "DOWN", etc (shown next); a way to serialize the object and retain reference equality - you have to write a readResolve method (not shown).
    class Direction {
        private final String name;
        private Direction (final String name) {
            this.name = name;
        public static final Direction UP = new Direction("UP");
        public static final Direction DOWN = new Direction("DOWN");
        public static final Direction LEFT = new Direction("LEFT");
        public static final Direction RIGHT = new Direction("RIGHT");
        public String toString() {
            return name;
    }Once you've written this code for one type-safe enum, you've written them for them all. You copy-cut-paste, and rename the class/elements. All this code is predictable. It is "boiler plate". Now, if you gave me a compiler that generated all this code for me, when I present it with
    enum Direction {UP, DOWN, LEFT, RIGHT}; then I've got something that reduces my boiler plate code to zip.... Enter the Java 1.5 compiler.

  • Using Serializable interface

    Hi, I have to write a program that implements the Serializable interface along with a LinkedList. It looks like this:
    public class Library implements Serializable{
       private LinkedList<LibraryBranch> collection;
    }However, all of my methods after that give a warning/error "class, interface, or enum expected." Do I have to write my own methods for Serializable that allows me to read and write data? I don't completely understand the Serializable interface description in the API.
    Thanks for your help.
    - Jeremy

    I don't know, the assignment asks for it. I think I have to be able to write the objects into a file and read them back again later.

  • Getting feilds in place of enum properties through jar.

    Hello
    I am faced a very strange problem in my code.I made a serializable class,a few public fields in it and a public enum.
    Now i pack the class in a jar and deploy it.When i try to access the properties of the enum,i get the feilds!!
    Can anyone please help me find the reason to it?
    Thanks and Regards
    Mansi

    MansiSachar wrote:
    Hello kajbj
    Altgough i have been trying to keep my query explanatory enuf but even then , if you want me to explain it more i wud do that......
    My class file is like :
    public class MyClass {
    public enum MyEnum {
    VALUE1
    public String VALUE2= "AnyValue";
    }Now wen i try with :
    MyClass.MyEnum.
    to access VALUE1,I am getting VALUE2 in its option not VALUE1.
    Hope you clear with the problem this time!No, you still haven't described how you validate that you are getting the wrong number. You did in your previous reply only say that eclipse is showing you wrong, nothing else. Where does it display the wrong value? When does it display the wrong value? What does you classpath look like? Do you still have the source files on the class path.
    You have left out almost everything that is relevant.

  • BlazeDS serializing Enum as Object instead of String

    Hi,
    we're having a problem with the serialization of our Java enums to Actionscript strings. The documentation says that by default, BlazeDS serializes an enum to an actionscript string.
    We only get [object Object] however and if I create a fake enum class in Actionscript we get [object enumName] as a result. The property is of enum type in the Java class and of String type in the actionscript class.
    I've looked around for solutions on the web but all I can find are examples to provide you with some kind of Actionscript "enum" functionality, while all we want is the default functionality of BlazeDS to work.
    The classes are:
    Java DocumentSearchResultTypeEnum:
    package be.brail.a327.model.enumeration;
    * Enum with the type of result: folder or document
    public enum DocumentSearchResultTypeEnum {
        FOLDER, DOCUMENT
    Java DocumentSearchResultDto:
    package be.brail.a327.model.dto.search;
    import org.apache.commons.lang.math.NumberUtils;
    import be.brail.a327.model.dto.AbstractValidityDto;
    import be.brail.a327.model.dto.annotation.RiaNumber;
    import be.brail.a327.model.enumeration.DocumentSearchResultTypeEnum;
    * Result of a search for documents
    public class DocumentSearchResultDto extends AbstractValidityDto {
        private static final long serialVersionUID = -4645818109238956407L;
        @RiaNumber
        private String parentId;
        private String description;
        private DocumentSearchResultTypeEnum type;
         * {@inheritDoc}
         * @see be.brail.a327.model.dto.AbstractDto#getStringInfo()
        @Override
        public String getStringInfo() {
            StringBuilder sb = new StringBuilder();
            sb.append("[id=");
            sb.append(this.getId());
            sb.append("[parentId=");
            sb.append(this.getParentId());
            sb.append("[type=");
            sb.append(this.getType().toString());
            sb.append("[description=");
            sb.append(this.getDescription());
            sb.append("]");
            return sb.toString();
         * Set the description.
         * @return the description
        public void setDescription(String description) {
            this.description = description;
         * Get the description.
         * @return the description
        public String getDescription() {
            return description;
         * Set the parentId.
         * @return the parentId
        public final void setParentId(String parentId) {
            this.parentId = parentId;
         * Get the parentId.
         * @return the parentId
        public final String getParentId() {
            return this.parentId;
         * Set the type.
         * @return the type
        public void setType(final DocumentSearchResultTypeEnum type) {
            this.type = type;
         * Get the type.
         * @return the type
        public DocumentSearchResultTypeEnum getType() {
            return type;
         * Overrides the equals
         * @see java.lang.Object#equals(java.lang.Object)
        public boolean equals(Object o) {
            if (o instanceof DocumentSearchResultDto
                    && NumberUtils.toLong(((DocumentSearchResultDto) o).getId()) == NumberUtils.toLong(this.getId())) {
                return true;
            } else {
                return false;
    Actionscript DocumentSearchResultTypeEnum:
    package be.brail.a327.console.model.enum
        [RemoteClass(alias= "be.brail.a327.model.enumeration.DocumentSearchResultTypeEnum")]
        public class DocumentSearchResultTypeEnum
            public static const FOLDER:String = "FOLDER";
            public static const DOCUMENT:String = "DOCUMENT";
    Actionscript DocumentSearchResultDto:
    package be.brail.a327.console.model.dto
        import be.brail.a327.console.model.enum.DocumentSearchResultTypeEnum;
        import be.brail.a327.dto.AbstractValidityDto;
        import mx.collections.ArrayCollection;
        [RemoteClass(alias = "be.brail.a327.model.dto.search.DocumentSearchResultDto")]
        public class DocumentSearchResultDto extends AbstractValidityDto
            public var parentId:String;
            public var description:String;
            public var type:String;
            [Transient]
            public var isBranch:Boolean = true;
            [Transient]
            public var children:ArrayCollection;
    Type in DocumentSearchResultDto is always "[object Object]" (or "[object DocumentSearchResultTypeEnum]" if we map the DocumentSearchResultTypeEnum class).
    What are we doing wrong?
    Thx in advance!

    Hey
    just have a look at the Date-Class there is the parse()
    method which is static and the parameter is a string.
    Cheers
    Dietmar

  • Enums over IIOP issue

    When trying to serialize java5 enum types over iiop (e.g. using the wlogic.jar client), you'll get a Mismatched serialization UIDs-exception (tested with WLS 10.3). This derives from a known bug or an omission in the java5 specification. There's a good description here, unfortunately in german only:
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6277781
    You can either use weblogic.jar to avoid IIOP or overwrite the default serializer class as a workaround. But I would like to know if the issue is already adressed at Oracle and if there will be a fix in the near future.
    Regards,
    Thomas

    No information on this issue?

  • Use Enum or Inheritance to determine a class subtypes.

    Hi people,
    I have to make a decision to model my domain objects. Let say that i have to model a Contact and ContactTypes. Well i can achive this making an abtract Contact class and extends this with, for example, PhoneContact, EmailContact, etc.. or can i make a Contact class with a enum member. This enum member can have defined these types of contacts.
    Option1:
    public abstract class Contact implements Serializable {
         private Integer id;
            getters & setters..
    public class PhoneContact extends Contact implements Serializable {
         private String description;
            getters & setters..
            @Override
            public String toString() {
                return "Phone Contact";
    public class EmailContact extends Contact implements Serializable {
         private String description;
            getters & setters..
            @Override
            public String toString() {
                return "Email Contact";
    }Option 2:
    public enum ContactType {
         PhoneContact,
         EmailContact
    public abstract class Contact implements Serializable {
         private Integer id;
            private ContactType type;
            getters & setters..
    }Can someone tell me what is the best aproach? the advantages an disadvantages on using one of these two options?...
    Thanks!.
    Mauro.

    I think, to make them more equivalent, you should move an abstract method (not the abstract class itself) into the enum body itself, and then have each of the enum values implement that method. (I'll call this option #3). Then option #1 and option #3 boil down to style and/or convenience. The advantage to using the enum is if a series of discrete values exist (for example, mapping to a database code/lookup table). For option #1, you really should use an interface rather than (or in addition to) your abstract class.
    - Saish

  • JAXB: Problem generating java enums

    Hi
    I'm having som problems configuring JAXB to generate type safe enums. The schema I'm using has several structures similar to this simplified example:
        <xs:element name="Car">
            <xs:complexType>
                <xs:sequence>
                    <xs:element name="CarTypeEnumInComplexType">
                        <xs:simpleType>
                            <xs:restriction base="xs:string">
                                <xs:enumeration value="Truck"/>
                                <xs:enumeration value="Jeep"/>
                                <xs:enumeration value="SUV"/>
                            </xs:restriction>
                        </xs:simpleType>
                    </xs:element>
                </xs:sequence>
            </xs:complexType>
        </xs:element>In the resulting Java code CarTypeEnumInComplexType is just generated as a String value in the Car Interface.
    What I really want is a separate Java class for "CarTypeEnumInComplexType" - with constants for each enumeration value.
    However, I do not want to change the schema - as this is maintained by another company.
    For a moment I thought I'd found the solution: By setting the global binding setting "typesafeEnumBase" to "xs:string" I made JAXB generate this kind of enumeration classes in cases like this:
    <xs:simpleType name="CarTypeEnum">
            <xs:restriction base="xs:string">
                <xs:enumeration value="Truck"/>
                <xs:enumeration value="Jeep"/>
                <xs:enumeration value="SUV"/>
            </xs:restriction>
        </xs:simpleType>However, I still can't make this work for enumerations nested within a complex type as illustrated in the first example.
    I'm new to XML schemas and JAXB - so I may be missing something obvious here...
    Is there any way to make JAXB generate an enum class for "CarTypeEnumInComplexType" in my first example without altering the schema structure?
    Vidar

    Well I couldnt really find any clear documentation to this , however with this post I was able to get going in the right direction I thought I would post the solution here.
    This assumes you have some control of your schema , it doesnt solve the problem where you cant touch the schema at all.
    So first my bindings.xjb file looks like:
    <?xml version="1.0"?>
    <jxb:bindings version="1.0" xmlns:jxb="http://java.sun.com/xml/ns/jaxb" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc" jxb:extensionBindingPrefixes="xjc">
         <jxb:bindings schemaLocation="CMSOSS.xsd" node="/xs:schema">
              <jxb:globalBindings typesafeEnumBase ="xs:string">
                   <xjc:serializable uid="12343"/>
              </jxb:globalBindings>
              <jxb:schemaBindings>
                   <jxb:package name="com.cms.oss"/>
                   <jxb:nameXmlTransform>
                        <jxb:elementName suffix="Element"/>
                   </jxb:nameXmlTransform>
              </jxb:schemaBindings>
         </jxb:bindings>
    </jxb:bindings>
    First its necessary to have the enum type defined outside of the complex type:
    <xs:simpleType name="serviceTypeEnum">
              <xs:annotation>
                   <xs:documentation>Type of service being added (RES, BUS, FAX, POTS)</xs:documentation>
              </xs:annotation>
              <xs:restriction base="xs:string">
                   <xs:enumeration value="RES"/>
                   <xs:enumeration value="BUS"/>
                   <xs:enumeration value="FAX"/>
                   <xs:enumeration value="POTS"/>
              </xs:restriction>
         </xs:simpleType>
    Then you can use the enum in your complex type in the following manner
         <xs:element name="service">
              <xs:annotation>
                   <xs:documentation>Create a service tag for each new line of service</xs:documentation>
              </xs:annotation>
              <xs:complexType>
                   <xs:sequence>
                        <xs:element ref="phone"/>
                        <xs:element name="type" type="serviceTypeEnum">
                             <xs:annotation>
                                  <xs:documentation>Type of service being added (RES, BUS, FAX, POTS)
                                  </xs:documentation>
                             </xs:annotation>
                        </xs:element>
                        <xs:element ref="lineDevice"/>
                        <xs:element ref="LNP" minOccurs="0"/>
                        <xs:element ref="VMPIN"/>
                        <xs:element ref="location"/>
                        <xs:element name="userService" minOccurs="0" maxOccurs="unbounded"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
    Some better documentation on this would sure help ... however I dont think this solves completely the original problem...
    I would think that type safe enums should be built into the specification without all this custom binding stuff.
    R
    S

  • Serialization of complex hierarchies using PortableObject or PofSerializer

    Hi, I am starting with Coherence and I am having a hard time trying to introduce POF serialization in a complex hierarchy of classes... classes containing another classes that extend abstract classes that extend another abstract classes... All of them add up to 500 classes... I tried using PortableObject and Cohclipse to generate automatically the readExternal and writeExternal methods but I noticed that I missed that data of the attributes contained in the abstract classes. I thought that it might be because I repeated in the subclass the indexes for the attributes of the abstract class but I changed it and it is still not working. Besides I have problems with Enums...
    I just wanted to know which would be the best approach to this kind of task because I am trying to look for posible solutions in google but all I can find are just very simple examples... If you could give me any advise I would really appretiate it. Thanks

    In Coherence 3.7 you can use annotations for por serialization, Coherence introduced two annotation: Portable and PortableProperty, that could make it for you easy to add por serialization without writing read/write external methods. Also it can automatically set the indexes so you avoid messing witht hem.
    Thanks a lot,
    Carlos Curotto.

Maybe you are looking for