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;

Similar Messages

  • 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

  • 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

  • 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?

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

  • 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'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).

  • Enum type class hierarchy.

    Hi,
    I was reviewing and eagerly testing the Typesafe Enum Facility (enum types) on 1.5.0 beta, which is still in Public Review in the JCP (JSR-201).
    I would would like to mention a missing feature that I find usefull and powerfull for a custom framework architecture.
    I understand and agree with respect to the first question on the JSR 201 FAQ, about subclassing enums.
    Having enumeration constants from both the superclass and the subclass is quite confusing and I agree with disallowing it from the language.
    But I miss the ability to inherit custom behavior (methods, and not enumeration constants), for an enum type, from a middle superclass. This middle superclass could be a base class for enum types within a specific development framework (and of course, java.lang.Enum would by in is class hierachy).
    The actual proposal allows for an enum type to only have java.lang.Enum as superclass, from which it inherits methods like name() and ordinal(). But in a proyect where a large number of diferent enum types with a common and custom extra framework behavior (like a localizedName() or propertyKey() method for example) would need the implementation of this behavior in each enum type source code (or in a helper class).
    Following the example above, the actual proposal would need the following coding in order to add an additional behavior to all (or some) of the enum types in a development proyect:
    public interface MyBaseFrameworkEnum {
         String localizedName();
         String propertyKey();
    public enum FooEnum implements MyBaseFrameworkEnum {
         FOO_A, FOO_B;
         public String localizedName() {
              //..... coding necesary in every enum implementing BaseFrameworkEnum
         public String propertyKey() {
              //..... coding necesary in every enum implementing BaseFrameworkEnum
    As you see, every enum type in my example framework (like FooEnum) would need to code both methods localizedName() and propertyKey() which would produce a lack of centralized code and increase of class file size.
    It would be very powerfull to be able to use the following coding:
    public abstract enum MyBaseFrameworkEnum {
         public String localizedName() {
              //..... coding centralized
         public String propertyKey() {
              //..... coding centralized
    public enum FooEnum extends MyBaseFrameworkEnum {
         FOO_A, FOO_B;
    As you see, with this abstract enum MyBaseFrameworkEnum (which does not falls in the subclassing problem mentioned in the FAQ) does not define enum constants and will pass its custom behavior to its subclass enums. thus centralizing the related code.
    I generally use an implementation of the Typesafe Enum Pattern so I really am looking forward for this new Typesafe Enum Facility in the Java language. But, as an example, I generally use common features in my enums, a properyKey() method used to get a unique key in order to internationalize my applications, since a description to enums is normally needed to be displayed to users.
    I believe this capability would be very powerfull in cases where common features are needed for enums in a development proyect with respect of:
    - code centralization and maintainance.
    - class file size.
    - source code readability.
    This extension would not contradict the actual definition, it would only allow for an enum type to be able to extend from another abstract enum type which has no enumeration constants.
    I believe that if there are other programmers that find this extension worth, it could make it in the JSR-201(which is in public review until February 21th) process before the final specification.
    Regards,
    Luis Longeri

    It would be very powerfull to be able to use the
    following coding:
    public abstract enum MyBaseFrameworkEnum {
         public String localizedName() {
              //..... coding centralized
         public String propertyKey() {
              //..... coding centralized
    public enum FooEnum extends MyBaseFrameworkEnum {
         FOO_A, FOO_B;
    }Luis, I like your idea but don't really like the idea of an abstract enum. I think this would be better
    public class MyBaseFrameworkEnum extends Enum {
         public String localizedName() {
              //..... coding centralized
         public String propertyKey() {
              //..... coding centralized
    public enum FooEnum extends MyBaseFrameworkEnum {
         FOO_A, FOO_B;
    }However, this always opens up the risk of you breaking the enum specific stuff, so all the vulnerable Enum methods would need to be declared "final".
    Because you are unlikely to see this in the language any time soon (if at all), you can always centralise your code in some static methods that take the enum as an argument
    public class MyBaseFrameworkEnumTools {
         public String localizedName(Enum e) {
              //..... coding centralized
         public String propertyKey(Enum e) {
              //..... coding centralized

  • General design Q: Should I use an Enum value as a factory?

    So in Java 5.0 we have the typesafe enums. I am just starting to learn them. I basically have a schedule of recurring events that have a series of rules to determine when the event recurs... There are only a few types of rules:
    ByMonth, ByWeek, ByDay ...
    Each of these enumerated values has a class associated with it that defines the rule (and is used to check to see if a particular day fills the requirenments for the rule).
    So my thoughts were: what is the best means of generating an instance of the Rule?
    1) Have a single RuleFactory class that switches on the RecurType enum value
         //... in some factory class...
         switch(recurType)
              case RecurRuleType.ByMonth : return new ByMonthRecurRule();
              case RecurRuleType.ByDay     : return new ByDayRecurRule();
              //...2) Define a factory method inside of the enum that does the job
    public enum RecurRuleType {
         ByDay { RecurRule getNewRule() { return new ByDayRecurRule(); } },
         ByMonth { RecurRule getNewRule() { return new ByMonthRecurRule(); } };
         abstract RecurRule getNewRule();
    }Or does it make no difference?

    I would go with the second one. Much easier to
    document.Thanks. I was worried that maybe dispersing the creation like that might be a programming no-no. It does have the benefit that if I want to add more enum values, I don't then have to go and change a factory class as well as the enum...

Maybe you are looking for

  • Can't find other computers on the network

    Ok, so I have a wrt54g wireless router thats directly connected to my main desktop pc.  I have another pc and a laptop that's set up wireless.  I'd like to link them to the main desktop so I can access files and the printer.  I can't seem to figure i

  • Encoding conversion in Swing?

    Hi, In working with text file, there is a default encoding to convert the charset into java String. We can check it with System.getProperty("file.encoding"). How about in Swing component? Is there another default encoding to convert the text input in

  • HT5239 Where can I get Apple FIPS Role guide for user so that I can use the APIs from my application

    I am trying to use Apple's FIPS certified crypto library's crypto APIs in my application to do the crypto operations. For that I was asked to refer the "Role Guide : User" in the nist document. But I couldn't find the same. Can I know where I can dow

  • My ipod has nothing on it it was wiped out how do i fix it

    my Ipod was wiped out nothing on hard drive at all how do i get a operating system back on it <Edited by Host>

  • Drill down report in EBS

    Hello Experts, we are implementing oracle EBS R12.1.3 for our one of the client, and they want the feature like drill down reports. As per my knowledge we cannot create drill down report using oracle reports builder. client doesnt have license for or