Mapping typesafe enums

I have a class, one of it's attributes is a typesafe enum:
public class Title {
     TitleType type;
     int titleId;
     String titleName;
     public TitleType getTitleType() {
          return this.type;
public class TitleType {
     private final String name;
     private final int typeId;
     private TitleType(String name, int typeId) {
          this.name = name;
          this.typeId = typeId;
     public String toString() {
          return this.name;
     public int toInt() {
          return this.typeId;
     public static final TitleType MAIN_TITLE = new TitleType("MAIN", 1);
     public static final TitleType SUB_TITLE = new TitleType("SUB", 2);
}My table is:
TITLES (
title_id numeric,
title_type varchar,
title_name varchar)
How do I map the TitleType class/attributes' String value to the column title_type in titles?
For a title with TitleType TitleType.MAIN_TITLE my table should look like:
title_id     title_type     title_name
1          MAIN          "The Guiness book of records"Regards,
Anthony

Thanks Doug,
I created the AfterLoad class and unmapped the field.
For some reason though all the titles loaded from the table are coming through as just "MAIN" TitleType.
Heres the AfterLoad class:
public class AfterLoad {
     public static void afterLoadTitle(Descriptor descriptor) {
          ObjectTypeMapping otm = new ObjectTypeMapping();
          otm.setAttributeName("titleType");
          otm.setFieldName("TITLE_TYPE");
          otm.addConversionValue(TitleType.MAIN_TITLE.toString(), TitleType.MAIN_TITLE);
          otm.addConversionValue(TitleType.SUB_TITLE.toString(), TitleType.SUB_TITLE);
          otm.addConversionValue(TitleType.TRANSLATED_TITLE.toString(), TitleType.TRANSLATED_TITLE);
          otm.setDescriptor(descriptor);
          descriptor.addMapping(otm);
}Any idea why?
Regards,
Anthony

Similar Messages

  • ORing TypeSafe enums together

    I have tranaslated an enum type from C using the "typesafe enum pattern" (see, e.g. Bloch: Effective Java, p.104). I want to OR two of the enum values together. E.g.
    Classname.FIRST | Classname.SECOND
    but because they are instances of a class and not int values I get an "operator cannot be applied..." error from the compiler. How can I augment/modify the class to make this operation legal and correct?
    Many thanks.

    You would need to associate an integer ordinal with each enum. Josh demonstrates something like this later in the chapter for an enum that implements Comparable. Since you want to work with bitwise values, you'll need to make each successive ordinal a power of two so each enum maps to one bit. It might look something like this: public class MyEnum implements Comparable {
        /** ordinal of next enum to be created */
        static private int nextOrdinal = 1 ;
        /** returns next ordinal to assign */
        static private int getNextOrdinal() {
            int thisOrd = nextOrdinal ;
            nextOrdinal <<= 1 ;
            return thisOrd ;
        /** face name of this enum */
        private final String name ;
        /** bitwise ordinal for this enum */
        private final int ordinal = getNextOrdinal() ;
        private MyEnum(String name)    { this.name = name ; }
        public String toString()       { return name ; }
        public int getOrdinal()        { return ordinal ; }
        public int compareTo(Object o) { return ordinal - ((MyEnum)o).ordinal ; }
        static public final MyEnum FIRST  = new MyEnum("First") ;
        static public final MyEnum SECOND = new MyEnum("Second") ;
        static public final MyEnum THIRD  = new MyEnum("Third") ;
        static public final MyEnum FOURTH = new MyEnum("Fourth") ;
    } Then, two enums are "OR'd" together like so: MyEnum.FIRST.getOrdinal() | MyEnum.SECOND.getOrdinal().

  • Typesafe Enums

    I do not use J2SE 5.0, and I need to use an enumerator-like construct. My original code was:
    // Constants to be used with runnersOnBase
    public static final short RUNNER_ON_FIRST = 1;
    public static final short RUNNER_ON_SECOND = 2;
    public static final short RUNNER_ON_THIRD = 4;Obviously this is not a great practice, so I decided to try typesafe enums, which are explained here: http://java.sun.com/developer/Books/shiftintojava/page1.html#replaceenums
    The problem I'm having comes from the fact that, in my program, I can add the integer constants together. Is there a similar way to do that with typesafe enums, and if so, how should the enum class be set up? Thanks a lot. Take care.

    The problem I'm having comes from the fact that, in
    my program, I can add the integer constants together.
    Is there a similar way to do that with typesafe
    enums, and if so, how should the enum class be set
    up? Thanks a lot. Take care.Something like
    public class Enum {
    private static Map enums;
    public static Enum A = new Enum();
    public static Enum B = new Enum();
    public static Enum C = new Enum();
    static {
       enums.add( Integer.valueOf( 0 ), A );
       enums.add( Integer.valueOf( 0 ), B );
       enums.add( Integer.valueOf( 0 ), C );
    public static Enum add( Enum a, Enum b ) {
       int av = enums.get( a );
       int bv = enums.get( b );
       Enum value = enums.get( Integer.valueOf( av + bv ) );
    //   if( value == null  ) throw some exception maybe?
       return value;
    }maybe?

  • Extending typesafe enum

    Hello,
    I know that this topic is already cleared that not possible to extend typesafe enum.
    But I don't have any other solution than doing this.
    Here is my problem.
    I have 2 package.
    - package generated
    - package design
    The purpose of the programs is to wrapping package generated in package design, that the user of this program should not use even the smallest part of the package generated.
    package generated contains class A, B, and enum Type
    Here are the declarations:
    File: generated/Type.java
    package generated;
    package generated;
    enum Type
    read, write, readwrite;
    }File: generated/B.java
    package generated;
    public class B
    int num;
    void setNum(int num){this.num = num;}
    int getNum(){ return num;}
    }File: generated/A.java
    package generated;
    public Class A
    int num;
    Type type;
    B b;
    void setNum(int num){this.num = num;}
    int getNum(){ return num;}
    void setType(Type type){this.type = type;}
    Type getType(){ return type;}
    void setB(B b){this.b = b;}
    B getB(){ return b;}
    }Now inside package design:
    File: design/B.java
    package design;
    public class B
    extends generated.B
    }File: design/A.java
    package design;
    public Class A
    extends generated.A
    }Here is the problem:
    File: App.java
    import design.*;
    class App{
    public static void main(String args[])
      A a = new A();
    B b = new B();
    a.setB(b);
    //This part is not expected, while it's using the type of package generated
    //a.setType( generated.Type.write);
    }The problem here is by setting the type of class A. While the method setType of design.A is inherited from generated.A, I cannot setting the value of this type without using the Type from the package generated, even when I add a enum of Type in package design, it still doesn't work, while there couldn't be casted from design.Type to generated.Type.
    This problem is not arised with setB(), while design.B is the subclass of generated.B, and thus can be casted automatically.
    So I have no Idea how can I solve this thing.
    As a note, the package generated cannot be changed.
    If there are anybody have ever faced the same problem, maybe can share their experience.
    Thanks a lot in advance.
    Best regards,
    Heru

    Hi,
    thanks for the reply.
    I'm actually making an API of a data source using JAXB to generate Java Code from an XML schema.
    This generated package is going to have features added along the time. So the wrapper I make is to assure that the API still work when new functions/features added. If I don't create any Wrapper, my written code (extension of the generated code) would be replaced by the new generated code each time the new features added.
    The reason I restrict the user to access the generated package, is because I don't want to confuse the user to access around the generated package and the wrapper package. The purpose of this wrapper is to completely wrapping whole the function of the generated code.
    Hopefully my explanation is understandable.. :-)
    Do you have any other advice how to accomplish this?
    Thanks.
    Best regards,
    Heru

  • Typesafe enum pattern

    Hi all,
    In the “Effective Java Programming Language Guide” by: “Joshua Bloch”, chapter: 5, item: 21, I came across the following:
    +“Constants maybe added to a typesafe enum class w/o recompiling its clients b/c the public static object reference fields containing the enumeration constants provide a layer of insulation bet. the client and the enum class.+
    What does that mean?
    The constants themselves are never compiled into clients as they are in the more common int enum pattern and its String variant.”
    What does that mean?
    Can someone please explain the above in more detail or guide me in another doc./article which helps me get the point?
    Any help is greatly appreciated.
    Edited by: RonitT on Apr 20, 2009 2:53 PM

    In any case, that item should be updated now to advise you to use the Enum types introduced in 1.5 instead of rolling yer own. You are right, I'll use that instead - looks like I have an old edition of book!
    Anyway. just for me to understand what you mentioned, since the client code sees the value of RANDOM -- like 17 and not 42 -- so let say my client code has the constants 0 thru 10 and now I need to add new constants from 11 to 20, if I'm confident that my client will never need these new constants, I don't need to give them the new code which contains the values 11 thru 20, is that right? That was you were trying to tell me?
    Thanks again.

  • Typesafe enums with private access - strange or useful?

    Given the class listed at the bottom, you'll notice that it's possible to specify a typesafe enum, and restrict that enum to clients in such a way that - and here's the strange part - the constant class is not exported in the api, despite the fact that it's required as an argument to the constructor.
    In other words you can legally state:
    MyClass myClass = new MyClass(MyClass.PLAIN);but not:
    MyClass.Constant constant = MyClass.PLAIN;
    MyClass myClass = new MyClass(constant);Anyone else noticed this? (Still coming to terms with the meaning of it).
    /k1
    Example code:
    * Type safety demo
    package blah;
    * Demo class showing the use of inaccessible constants
    public class MyClass {
         /** My first constant */
         public static final Constant FIRST;
         /** My second constant */
         public static final Constant SECOND;
         /* The instance constant field */
         private Constant constant;
         /* static initialiser for the constants */
         static {
              FIRST = new Constant("First");
              FANCY = new Constant("Second");
          * @param constant The constant spec
         public MyClass(Constant constant) {
              super();
              this.constant = constant;
         private static class Constant {
              private String name;
               * @param name The name of my constant
              public Constant(String name) {
                   this.name = name;
    }

    And indeed outside the package...
    package blah.test;
    import blah.*;
    public class Driver {
          * Main method for the sake of demonstration...
         public static void main(String[] args) {
              Object[] constants = MyClass.VALUES;
              for (int i = 0; i < constants.length; i++) {
                   System.out.println(constants);
                   MyClass myClass = new MyClass(constants[i]);
                   System.out.println(myClass);
    ...then...
    * Type safety demo
    package blah;
    * Demo class showing the use of inaccessible constants
    public class MyClass {
         /** My first constant */
         public static final Constant FIRST = new Constant("First");
         /** My second constant */
         public static final Constant SECOND = new Constant("Second");
         /** An array of the constants */
         public static final Constant[] VALUES = { FIRST, SECOND };
         /* The instance constant field */
         private Constant constant;
          * @param constant The constant spec
         public MyClass(Object constant) {
              super();
              if (constant instanceof Constant) {
                   this.constant = (Constant)constant;
         private static class Constant {
              private String name;
               * @param name The name of my constant
              public Constant(String name) {
                   this.name = name;
               * @return The name of the constant
              public String toString() {
                   return name;

  • Typesafe enums - 1.5

    In the interview Joshua Bloch states the the new 1.5 feature "Typesafe enums - Provides all the well-known benefits of the Typesafe Enum pattern"
    Does it also provide the pitfalls? The typesafe enum pattern is nice. However, in a multi-classloader environment it can behave unexpectedly. Similar to the Singleton pattern, it is generally best to avoid it in app-server code.
    Does the 1.5 implementation essentially compile to the pre-1.5 manual implementation or does it deal with this issue?

    you can overcome the and .equals() failing with a very minor amount of code. Basically you need a set of all possible typesafe values.
    Additionally you need to implement readResolve to prevent serialization from cloning.
    Finally - it's just never a good idea to use == for equality comparison. It should only be used for identity comparison (and even then most of the time you should have equals perform the identity comparison).
        private static final Stooge[] ALL = new Stooge{Moe, Larry, Curly};
        //see java.io.Serializable for details
        protected Object readResolve() throws ObjectStreamException {
            return getTypeFor(this.name);
        //you usually need this for retrieval from persistent storage
        public static Stooge getTypeFor(String name){
          Stooge result = null;
          for(int i = 0; i < ALL.length; i++){
            if(ALL.name.equals(name)){
    result = ALL[i];
    break;
    return result;

  • The predecessor to the "typesafe enum pattern"

    In 1998, Michael Bridges published the following on Dr.Dobb's Portal
    (http://www.ddj.com/windows/184403569):
    class BookAgeLevel
    private BookAgeLevel(){}    
    // Following are all the BookAgeLevel objects    
    // there will ever be.    
    final static BookAgeLevel TODDLER = new BookAgeLevel();    
    final static BookAgeLevel CHILD = new BookAgeLevel();    
    final static BookAgeLevel TEENAGER = new BookAgeLevel();    
    final static BookAgeLevel ADULT = new BookAgeLevel();    
    }In 1999, Nigel Warren and Philip Bishop refers to the exact same pattern as the "typesafe
    constant idiom" in their book "Java in Practice" (page 48):
    public final class Alienrace
      public static final AlienRace BORG = new Alienrace();
      public static final AlienRace FERENGI = new Alienrace();
      private AlienRace() {}
    }In 2000, Joshua Bloch refers to the following code as the "typesafe enum pattern" (http://java.sun.com/developer/Books/shiftintojava/page1.html):
    // The typesafe enum pattern
    public class Suit {
        private final String name;
        private Suit(String name) { this.name = name; }
        public String toString()  { return name; }
        public static final Suit CLUBS = new Suit("clubs");
        public static final Suit DIAMONDS = new Suit("diamonds");
        public static final Suit HEARTS = new Suit("hearts");
        public static final Suit SPADES = new Suit("spades");
    }

    sunfun99 wrote:
    No point, just interesting. There is no question attached to this.OK - I still have a load of code in both C++ and Java that uses this Pattern ( it ain't broke so I ain't fixing it) and I first started using this in C++ in about 1987 (God 20 years ago). I didn't invent it for myself so it must be older than that.

  • PersistenceDelegate for typesafe enum pattern

    I've converted my code over from using int constants to the typesafe enum pattern in Effective Java. Unfortunately, the pattern only goes into serialization using Serializable and does not go into how to write a proper PersistenceDelegate that parallels the safety precautions of the Serializable enum. I've tried to do a direct mirroring of the readResolve() method given in the book inside of the intiatiate method of my PersistenceDelegate, but the XMLEncoder keeps rejecting the output and I get an InstantiationException, which shouldn't happen since the method call should not instantiate any new instances since the enums are static.
    class PositionBiasModePersistenceDelegate extends PersistenceDelegate {
        protected Expression instantiate(Object oldInstance, Encoder out) {
            PositionBiasMode mode = (PositionBiasMode) oldInstance;
            return new Expression(mode, PositionBiasMode.VALUES, "get", new Object[] {new Integer(PositionBiasMode.VALUES.indexOf(mode))});
    public abstract class PositionBiasMode {
        private final String name;
        private static int nextOrdinal = 0;
        private final int ordinal = nextOrdinal++;
        /** Creates a new instance of PreferredPositionMode */
        private PositionBiasMode(String name) {
            this.name = name;
        public String toString() {
            return name;
        public abstract boolean complies(PositionBias pb);
        public static final PositionBiasMode IGNORE = new PositionBiasMode("Ignore") {
            public boolean complies(PositionBias pb) {
                return true;
        public static final PositionBiasMode FRONT = new PositionBiasMode("Front") {
            public boolean complies(PositionBias pb) {
                return pb.hasBias() && pb.getPositionBias() < 0 ? false : true;
        public static final PositionBiasMode BACK = new PositionBiasMode("Back") {
            public boolean complies(PositionBias pb) {
                return pb.hasBias() && pb.getPositionBias() >= 0 ? false : true;
        private static final PositionBiasMode[] PRIVATE_VALUES = {IGNORE, FRONT, BACK};
        public static final List VALUES = Collections.unmodifiableList(Arrays.asList(PRIVATE_VALUES));
    }

    Yeah I tried this too. I think the instantiation exception is something to do with it trying to recreate the MyEnum.VALUES List. I don't understand enough about the process to know how to fix that though.
    The approach I eventually went for was to add a couple of things to the enum class as follows:
    // add to MyEnum class:
    public static final PersistenceDelegate PERSISTENCE = new PersistenceDelegate()
         protected boolean mutatesTo(Object oldInstance, Object newInstance)
              return (MyEnum)oldInstance == (MyEnum)newInstance;
         protected Expression instantiate(Object oldInstance, Encoder out)
              MyEnum enum = (MyEnum)oldInstance;
              return new Expression(enum, new MyEnum.Factory(), "forOrdinal", new Object[]{new Integer(enum.ordinal)});
    public static final class Factory
         public MyEnum forOrdinal(int ordinal)
              return PRIVATE_VALUES[ordinal];
    // usage:
    XMLEncoder enc = new XMLEncoder(...);
    enc.setPersistenceDelegate(MyEnum.class, MyEnum.PERSISTENCE);Not entirely sure it's the ideal approach but maybe it'll work for you. Cheers.

  • TypeSafe Enums + readResolve + New Types

    I have the following code:
    public final class Type implements java.io.Serializable {
        public static final Type TYPEA= new Type ("TYPEA");
        public static final Type TYPEB= new Type ("TYPEB");
        public static final Type TYPEC= new Type ("TYPEC");
        public static final Type TYPED= new Type ("TYPED");
        private String type;
        public Type (String type) {
            this.type = type;
        public String toString() {
            return this.type;
        private static int nextOrdinal = 0;
        private final int ordinal = nextOrdinal++;
        private static final Type [] VALUES = { TYPEA, TYPEB, TYPEC, TYPED};
        Object readResolve() throws ObjectStreamException {
             return VALUES[ordinal];
    }My problem is that I want the user to be able to add a new type for example lets say TYPEF. how would I go about doing this and also make it work with serialiazable?

    you can overcome the and .equals() failing with a very minor amount of code. Basically you need a set of all possible typesafe values.
    Additionally you need to implement readResolve to prevent serialization from cloning.
    Finally - it's just never a good idea to use == for equality comparison. It should only be used for identity comparison (and even then most of the time you should have equals perform the identity comparison).
        private static final Stooge[] ALL = new Stooge{Moe, Larry, Curly};
        //see java.io.Serializable for details
        protected Object readResolve() throws ObjectStreamException {
            return getTypeFor(this.name);
        //you usually need this for retrieval from persistent storage
        public static Stooge getTypeFor(String name){
          Stooge result = null;
          for(int i = 0; i < ALL.length; i++){
            if(ALL.name.equals(name)){
    result = ALL[i];
    break;
    return result;

  • Enum or EnumMap to store String constants using enums?

    I have decided to use enums to store some String
    constants. What are the pros and cons of using a
    simple enum versus using EnumMap? What are
    the differences?
    If going with the simple enum option, I would just
    do as in the following example:
    // The typesafe enum pattern
    public class Suit {
        private final String name;
        private Suit(String name) { this.name = name; }
        public String toString()  { return name; }
        public static final Suit CLUBS =
            new Suit("clubs");
        public static final Suit DIAMONDS =
            new Suit("diamonds");
        public static final Suit HEARTS =
            new Suit("hearts");
        public static final Suit SPADES =
            new Suit("spades");
    }A System.out.println(CLUBS); prints out "clubs".
    Or is EnumMap a better choice? If so, why? If not,
    then why?

    jverd wrote:
    sunfun99 wrote:
    +3.1459378192030194732612839423...+ is a constant, but not a named constant. If I give the constant a name, like "PI", then I can use that name to access the constant (instead of having to repeat the long constant literal every time I want to use it). Now, I want to use a number of constants across various classes, so I give each of these constants a name. What I then have is a number of named constants. To name a constant means that I map a name to a value:That's not what "mapping" means in this context. Really? Even the Collections tutorial says it, "Map � an object that maps keys to values". And - not surprising - the classes/interfaces "Map", "Set", etc. are named so because they mimic these mathematical concepts.
    It appears you don't know what java.util.Map is for. java.util.Map is "an object that maps keys to values". It's an interface that also provides various methods that allows for various dealings with the data, such as removing or adding mappings, provide the value given the name, give the total number of mappings, etc.
    Then define an enum.As I said earlier, I believe you, and that's what I will do.
    What makes you think that EnumMap is a "more advanced implementation" of enums? (It's not. It's not an implementation of enums at all.) What does "more advanced" even mean here?Sorry, my mistake. It's not an implementation of enums. However, it takes enums as parameters. In that sense, using EnumMap would indirectly imply a more complicated way of using enums, since not only do I create enums, but then I have to put the into EnumMap.

  • What's the best way to use an enum to validate statuses

    I am trying to write and use an enum to represent a status code and validate status code values. Ultimately the input data from another system and the database will be 1 or 2 i.e.the indexes and the java code will use the LIVE and CANCELLED when referring to the status. The code I have written
    public class TestEntityStatus {
         private static EntityStatusImpl es;
         public static void main(final String args[]){
                    es =  new EntityStatusImpl();  
                    es.setStatusCode("1"); // valid test
                    es.setStatusCode("3"); // invalid test
    }The EntityStatusImpl class:
    public class EntityStatusImpl {
        private String statusCode;
        public EntityStatusImpl() {
        public final String getStatusCode() {
            return statusCode;
        public final void setStatusCode(final String statusCode) {
             String allStsIndexesAsRegExpr = "[";                                                                                 //
                EntityStatus allStatuses [] = EntityStatus.values();                                                     // would like to 
                for(EntityStatus e : allStatuses)                                                                                // put this code
                    allStsIndexesAsRegExpr = allStsIndexesAsRegExpr + e.getStatusCode();   // in the enum
                allStsIndexesAsRegExpr = allStsIndexesAsRegExpr + "]";                                        // EntityStatus
                System.out.println(" allStsIndexesAsRegExpr = " + allStsIndexesAsRegExpr);           //
                 if (statusCode.matches(allStsIndexesAsRegExpr)) {
                     this.statusCode = statusCode;          
                 else {
                      throw new IllegalArgumentException("Entity status " + statusCode + " is invalid");     
    }The EntityStatus enum has a method "getAllIndexesAsRegex" which I would like to call. However, my understanding of enums is preventing me from doing so.
    If I declared an EntityStatus, I expected that I would be able to get all of the indexes back as follows in
    EntityStatus x;
    x.getAllIndexesAsRegex();
    Instead I have to copied the code from the enum into the setStatusCode method above, where it works but does not seem to be in the right place.
    public enum EntityStatus {
                     LIVE(1), CANCELLED(2);
                     private int index;
                 private EntityStatus(int index) {
                     this.index = index;
                  public int getStatusCode(){
                           return index; 
                  public String getAllIndexesAsRegex(){
                       String output = "[";
                       PromiseStatus allStatuses [] = PromiseStatus.values();
                       for(PromiseStatus p : allStatuses)
                            output = output + p.getStatusCode();
                       output = output + "]";
                       return output;
         }The java tutorial doesn't seem to throw much light on this type of application of enums for me, neither does Herbert Schilt's excellent book on Java 5.
    Can anyone spot any flaws in my logic or suggest better ways of achieving this?

    If you want to ensure type safety and retrict the user to a range of values it seems to me you are over complicating
    the implementation. Simply change your Impl class accessor and mutator methods to accept and return the enum
    type respectively. For example:
    private EntityStatus entityStatus;
    public EntityStatus getEntityStatus()
       return entityStatus;
    public void setEntityStatus(EntityStatus entityStatus)
      if (entityStatus == null)
        throw new IllegalArgumentException("Invalid entity status!");
      this.entityStatus = entityStatus;
    }The one downside is that you are retrieving the actual underlying enum values from external source systems which you need to map back to your
    enum types. Unfortunately the Enum class does not have a method that will return what you need (the valueOf method returns the enum type
    based on the enum name). However you can provide a method in your enum class that will map the external source values to the enum. Below is
    one such implemetation.
    import java.util.HashMap;
    import java.util.Map;
    public enum EntityStatus
      LIVE("1"),
      CANCELLED("2");
      private String statusCode;
      private static Map<String,EntityStatus> enumMap = new HashMap<String,EntityStatus>(EntityStatus.values().length);
      static
        enumMap.put(LIVE.getStatusCode(),LIVE);
        enumMap.put(CANCELLED.getStatusCode(),CANCELLED);
      private EntityStatus(String statusCode)
        this.statusCode = statusCode;
      public String getStatusCode()
        return statusCode;
      public static synchronized EntityStatus deriveObject(String statusCode)
        return enumMap.get(statusCode);
    }Below is a usage example:
      public static void main(String args[])
        EntityStatus status1 = EntityStatus.deriveObject("1");
        EntityStatus status2 = EntityStatus.deriveObject("2");
        EntityStatus status3 = EntityStatus.deriveObject("3");
        System.out.println(status1);
        System.out.println(status2);
        System.out.println(status3);
      }

  • Enum's

    I am trying to create an enum type Suit as follows:
    public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }
    I've tried it with and without a ';' at the end, and either way, I get essentially these two errors:
    Card.java:3: ';' expected
    public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }
    ^
    (the '^' symbol is displayed right under the '{' in the command editor).
    ...and this error:
    .\Suit.java:3: 'class' or 'interface' expected
    public enum Suit {
    ^
    The Java tutorial is inconsistent, and of no help in solving this mystery.
    Any help you can give will be appreciated.
    Orion

    To clarify: enums didn't exist in 1.4, so it sees
    enum as a type name and Suit as a variable name.oh! i could have sworn they did.
    what did one use in 1.4? just a bunch of final
    vars?typesafe enum pattern :
    http://java.sun.com/developer/Books/effectivejava/Chapter5.pdf(see chapter 21)

  • Enum code too large 64k limit

    While compiling with JDK1.5 received a "code too large" error when trying to compile an enum. Apparently the 64k limit is imposed on the new enum spec.
    This restriction doesn't allow for enums with a large set of values which is impractical at best.
    Has anyone else encountered this problem and received any response from Sun?

    Sorry I should further explain the "impractical" meaning.
    Consider the example code:
    public enum MyEnum
    FIRST( 1, "One" ),
    SECOND( 2, "Two" ),
    THIRD( 3, "Three" );
    private final Integer value;
    private final String label;
    private MyEnum( final Integer value, final String label )
    this.value = value;
    this.label = label;
    public Integer getValue()
    return this.value;
    public String getLabel()
    return this.label;
    The "impractical" part comes in where I'm limited by the enum constant statement string of 64k. So, if I have several enums with even modest lengthed labels I'm stuck. I currently am able to implement this in JDK 1.4 using typesafe enum pattern. I would like to implement the same way using enums in JDK 1.5.

  • ENUMS

    I have a few quick questions about using ENUMs - and why they are so good?
    After having read the documentation on them on sun.com, and my own textbook notes, I'm still not entirely clear about using them.
    I know you should use them when you have a fixed set of constants (such as days of the week, status' for something).
    But for the lets say, day variable, why it can't just be a string of "Monday" or whatever.
    Do you use ENUMS to stop you from entering something that shouldnt exist?
    Someone also has said to use them as they are quite powerful, how exactly?
    I'm not sure if I've understood this properly!!

    f1d wrote:
    I have a few quick questions about using ENUMs - and why they are so good?
    After having read the documentation on them on sun.com, and my own textbook notes, I'm still not entirely clear about using them.
    I know you should use them when you have a fixed set of constants (such as days of the week, status' for something).
    But for the lets say, day variable, why it can't just be a string of "Monday" or whatever.Well, let's try that:
    public class DayOfWeek {
        private String day;
        public DayOfWeek(String day) {
            this.day = day;
    DayOfWeek appointment = new DayOfWeek("Fooglesday");Uh oh.
    Yeah, a user isn't likely to input "Fooglesday", but they might easily input "Satruday".
    You could add a bunch of if/else statements or the like to confirm that the value is a known day of the week...but enums are easier.
    Do you use ENUMS to stop you from entering something that shouldnt exist?Yes, exactly.
    Someone also has said to use them as they are quite powerful, how exactly?
    I'm not sure if I've understood this properly!!They're basically a semi-automatic implementation of the typesafe enum pattern. That is to say, they're classes, and have all the advantages as such (so you can define special behavior in them), and they also have a limited set of possible values, which prevents mistakes like the above, and they also have language support, so you can use them with less code (and more clarity).

Maybe you are looking for