Extending enums

The new enums in java will solve the problem of using integer constants... but they will not work when you want to use the constants as a set of values....
i.e.
static final int BLUE  = 1;
static final int GREEN  = 2;
static final int RED = 4;
int myColors = BLUE | GREEN;So I propose the following extension?
enum Color { blue, green, red }
Set<Color> myColors = Color.blue | Color.green;I mean that the bitwise or operator ( | ) could be used to produce a Set of enum values. This set could be implemented as a BitSet internaly (for performance).
With this the new enums can be be used in every place you used to use integer constants.
Aditionally the bitwise and operator ( & ) could be overloaded to check if a Set<EnumType> contains a enum member .

Sounds like you need operator overloading. Not that
that's necessarily a bad thing, especially if operator
overloading can be introduced in a way that strongly
discourages abuse.Yes, it requires operator overloading, but it is a special case, like with strings. The bitwise or should be overloaded for enum members to result in a EnumSet, like the plus operator is olverloaded to strings to build the concatenated string.
It is an operator overloading introduced by the compiler, to improve the enums usability, and code readability.
Without this addition, people will keep away from using enums when this kind o functionality (passing a set of enum values to a funtion) is needed. They will create integer constants with values of powers of 2 (1, 2, 4...) and pass them combinated with | as an int, like it always was done in C. The enums are made to substitute integer constants, but the inability to create a set of them (in a easy way) will keep people from using them.

Similar Messages

  • Extending enums during runtime

    Hey folks,
    i have a question concerning enums. Is it possible to extend enums during runtime? For example i have following enum:
    public enum MyValues
    VALUE1, VALUE2, VALUE3
    }is it possible that i have a method for example which adds VALUE4 and VALUE5 to this enum???
    Thanks alot.
    Ohno

    No, it wouldn't make sense.
    The point of enums is that the possible values are known at compile time so that you can, for example, use them as switch cases.
    If extra values are being added at run time you probably want some kind of Map.

  • Extendable Enums

    I am somewhat new to Java but experienced in C++. After looking online and in "Thinking in Java", I am still at a loss for how to solve my problem. I am building a package that will be used in various other larger projects. Within this package I have an enum, defined within a class as shown below. This is meant to be the set of enums common to all high level projects. The problem is that each project needs to add a few to the list. How can I get the common class containing the default set of enums to also include the additional ones defined outside my base package which I don't want the proejct developer to modify?
    public class A  {
        public enum Peripherals {
            LED1(20),
            LCD1(23);
        private final int id;
        private Peripherals( int id) { this.id = id; }
        public int getId() { return id; }
    }I was thinking of maybe changing the above class to contain an EnumSet that stores classes that implement an interface. If I put my base enums in a class that implements an interface and the project developer does the same would that somehow work?
    Thanks in advance for your help.

    Hi,
    Heres a bit of code that might help you understand enums a bit better.
    public class A {
            public enum Colour{
                    Red, Green, Blue
            public static void main (String []args){
                    String [] colours = {"Red", "Green", "Blue"};
                    for (String str : colours) {
                            switch (Colour.valueOf(str)) {
                                    case Red : System.out.println("Red");
                                               break;
                                    case Green : System.out.println("Green");
                                               break;
                                    case Blue : System.out.println("Blue");
                                               break;
    }

  • Is there any way to extend an enum from other enum

    I using enums with some abstract methods etc. I created new enum and wanted to extend this with the prior and compiler tells it as error. Is there any workaround for extending enum to other enum ?

    You can have both enums implement the same interface and use them that way. Joshua Bloch alludes to this in Effective Java 2nd Edition.
    - Saish

  • Using static .values() method of Enum in Generic Class

    Hi *,
    I tried to do the following:
    public class AClass<E extends Enum<E> >  {
         public AClass() {
              E[] values = E.values(); // this DOESN'T work
              for (E e : values) { /* do something */ }
    }This is not possible. But how can I access all Enum constants if I use
    an Enum type parameter in a Generic class?
    Thanks for your help ;-) Stephan

    Here's a possible workaround. The generic class isn't adding much in this case; I originally wrote it as a static method that you simply passed the class to:
    public class Test21
      public static enum TestEnum { A, B, C };
      public static class AClass<E extends Enum<E>>
        private Class<E> clazz;
        public AClass(Class<E> _clazz)
        {  clazz = _clazz;  }
        public Class<E> getClazz()
        {  return clazz;  }
        public void printConstants()
          for (E e : clazz.getEnumConstants())
            System.out.println(e.toString());
      public static void main(String[] argv)
        AClass<TestEnum> a = new AClass<TestEnum>(TestEnum.class);
        a.printConstants();
    }

  • Help using the Foo SubFoo extends Foo SubFoo trick

    Please have a look at the following (simplified) excerpt:
    import java.util.*;
    public class Vertex<V extends Vertex<V>>
    private List<V> sources = new ArrayList<V>();
    public void addEdgeTo (V target)
    // #1: Following leads to: cannot find symbol
         // symbol : method add(omr.test.Vertex<V>)
         target.sources.add(this);
         // #2: Following leads to: warning: [unchecked] unchecked cast to type V
    target.sources.add((V)this);
    I have already studied the very interesting article "Groking Enum (aka Enum<E extends Enum<E>>)" on http://madbean.com/blog/62/ . And I'm using that trick, since I want any instantiation of my Vertex class
    to record links (via the "sources" list) to its source vertices, all being homogeneous.
    In other words, all the vertices are meant to be instances of the same Vertex subtype.
    How do I code this?
    Attempt #1 does not compile
    Attempt #2 works, but gives the "unchecked" warning, something I'd like to avoid...
    Any idea?
    Thanks,
    /Herv�

    Here is a reply to my own post, which solves the original problem:
    import java.util.*;
    public class Vertex<V extends Vertex<V>>
    // Vertices that point to this vertex
    private List<V> sources = new ArrayList<V>();
    // Vertices that this vertex points to
    private List<V> targets = new ArrayList<V>();
    // Add a directed edge between 'source' vertex and 'target' vertex
    public static <V extends Vertex<V>> void addEdge (V source, V target)
    source.targets.add(target);
         target.sources.add(source);
    // And a similar method for removeEdge
    Now both 'source' and 'target' parameters of the addEdge() method are provided at run time and their (identical) subtype properly inferred.
    It compiles and runs OK, and is clear (more symmetrical).
    Bye,
    /Herve

  • Passing any enum type to a method

    Consider I have created some enums:
    public enum Day {
        SUN, MON, TUE, WED, THU, FRI, SAT
    public enum Month {
        JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC
    }I want to create a method that will accept any type of enum and display all values. So the call would look something like:
    showAll(Day);
    showAll(Month);I'm not sure what to pass to the method. My understanding of Generics is rudimentary at best, despite reading the tutorial several times now. Here is some uncompilable code that might illustrate:
    public void showAll(EnumType enumType)  // <--- not sure what to pass here
      Enum[] allValues = enumType.values();
      // then, loop over the allValues array and I can proceed from here
    }The actual code is needed is for displaying a list of checkboxes to the user where the input is the enum class, and the checkboxes are every enum value.

    brucechapman wrote:
    You could use this signature
    <T extends Enum<T>> void showall(Class<T> clazz); Then use reflection to invoke the values() method which you know is there because only Class objects for enums can be passed in.I'll be honest, that signature looks very strange to me. However, I tried it anyway and it worked even without reflection.
    public class PassingEnums
      public enum Day {
        SUN, MON, TUE, WED, THU, FRI, SAT
      public enum Month {
        JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC
      public <T extends Enum<T>> void showAll(Class<T> clazz)
        T[] types = clazz.getEnumConstants();
        for (int i = 0; i < types.length; i++)
          System.out.println(types.toString());
    public static void main(String[] args)
    PassingEnums test = new PassingEnums();
    test.showAll(Day.class);
    System.out.println("---");
    test.showAll(Month.class);
    }Or were you thinking of something else?
    I guess I'll have to hit the tutorials again, since that signature looks foreign to me.
    Thanks.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Overriding an enum type?

    Hi Java experts,
    I would appreciate some help about a small problem I have with some java code of my own. I'm using Java 1.5. I currently have written a class that takes a filename and extract records from a corresponding binary file. The structure of the file is known and is stored in a enum:
    public class ParseFile  {
        private static enum TicketField {
            FieldA(1, FieldType.TYPE_INT),
            FieldB(1, FieldType.TYPE_INT),
            FieldC(2, FieldType.TYPE_STRING),
            // Stores number of fields in record. BTW is this the right way to do it ?
            public static final int numberOfElements = TicketField.values().length;
            // Length of field in bytes.
            private int size;
            // Type of field, enumerated.
            private FieldType type;
            // Constructor.
            TicketField(int size, FieldType type) {
                this.size = size;
                this.type = type;
        public ARRAY fetchRows(String filename) {
        // Create a new row structure.
        Vector<Object> row = new Vector<Object>(TicketField.numberOfElements);
        // Extract rows according to definition of fields above.
        blah blah
        }With this code I can call fetchRows('my_file') and get the list of records in it. Now I would like to extend this piece of code to be able to process different types of files, with different number of fields, different fields definitions, etc; however the extraction algorithm, once the file structure is given, remains the same. I would eg call fetchRows('my_file_cll', type='cll'), fetchRows('my_file_cat', type='cat'), etc. The structure of the returned resultsets would differ btw.
    So conceptually I would like to subclass ParseFile, overriding not the method (fetchRows) but the enum... I can't think of a way to do this. Is it possible to define a kind of "abstract enum" that would be used in the code but instanciated only in a subclass? Otherwise is there a neat way to obtain this result in Java, avoiding to duplicate the code n times?
    Thanks for your help,
    Chris

    Maybe something on the lines ofpublic class EnumFieldTest<E extends Enum<E>>     {
      private final Enum<E>[] myEnum;
      public EnumFieldTest(Enum<E>[] myEnum) {
        this.myEnum = myEnum;
      public void printEnumValues() {
        for (Enum<E> enum1 : myEnum) {
          System.out.println(enum1);
      public static void main(String[] args) {
        new EnumFieldTest<TicketField>(TicketField.values()).printEnumValues();
    enum TicketField {
      FieldA, FieldB, FieldC
    }db

  • Enums... Im totally lost

    Im trying to write a class which - in one of its methods - needs to do an Enum.valueOf(clazz, val) for an enum type which is a property of the class.
    For example, suppose I've got an enum called TrafficLightStates, I want to be able to do something like this:
    MyClass myThing = new MyClass(TrafficLightStates.class);
    // This gets plugged in to some generic property binding framework,
    // but at some later point, something is going to call:
    myThing.setValue("RED");At this point, MyClass#setValue needs to dig out the enum value for "RED" (using Enum.valueOf) and pass it off to some underlying object which is getting populated.
    What Im getting totally stuck on is how I go about assigning the enum class as a member variable of MyClass. No matter what wierd and wonderful combination of generic declaration I try, I just cant get stuff to match up by the time I try to invoke Enum.valueOf (It needs an Enum<T extends Enum<T>>).
    Can anybody point me in the right direction?
    Many thanks,
    Dave

    I hope I haven't missed the point - or Im even more screwed ;o)
    Basically Im writing a PropertyEditorSupport implementation which does text <-> enum value conversion (I need to write a custom one because I want to handle the concept of "no value" <-> null).
    Clearly I dont want to write such a class for each enum type, I'd like to be able to do this:
    PropertyEditorSupport enumSupport = new MyEnumSupport(TrafficLightStates.class);And of course, it can be used elsewhere with any other enum type.
    To give an idea, here's the cheap-shot version which dodges the hard generic questions I cant work out the answers to and lives with the type safty warnings:
    public class CustomEnumEditor extends PropertyEditorSupport {
      private String emptyValueIndicator;
      private Class enumType;
       * Id ratther FORCE an enum to be supplied at compile time here..
      CustomEnumEditor(Class enumType, String emptyValueIndicator) {
        if (!enumType.isEnum()) {
          throw new IllegalArgumentException("Not an enum: " + enumType);
        this.enumType = enumType;
        this.emptyValueIndicator = emptyValueIndicator;
      @Override
      public void setAsText(String text) {
        if (emptyValueIndicator.equals(text)) {
          setValue(null);
        } else {
          // Here's where I dig out the value - and currently have to live
          // with a compiler warning
          Object value = Enum.valueOf(enumType, text);  
          setValue(value);
    }Hopefully Im not missing the point?
    ~D

  • Enum class

    i have written the code like the below.
    iam using Enum abstract class it is giving an error at class position.
    plz help me how to use the Enum class in our own classes.
    import java.io.*;
    import java.lang.*;
    public static final class MyBaseFrameworkEnum extends Enum {
    }

    Classes cannot extend enumerations.
    public class MyClass {
    public void myMethod(){
    private enum MyEnum {
            SOMETHING1("something"),
            SOMETHING2("something"),
            SOMETHING3("something"),
            SOMETHING4("something"),
            private String fieldName;
            MyEnum(String fieldName){
                this.fieldName=fieldName;
            public String getFieldName() {
                return fieldName;
    }or...
    public enum MyEnum {
            SOMETHING1("something"),
            SOMETHING2("something"),
            SOMETHING3("something"),
            SOMETHING4("something"),
            private String fieldName;
            MyEnum(String fieldName){
                this.fieldName=fieldName;
            public String getFieldName() {
                return fieldName;
        }Anyway, fiddle around with it.

  • 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

  • Enum type as generic

    In the following, what should X be so that E is recognized as an enum type?
    class A<E extends X> {
        . . . E.values() . . .
    }It seems that X of Enum<E> should work, but no joy. I thought that enum types were subclasses of java.lang.Enum, but apparently not fully.

    Enum<E> does not have a method values(). The compiler generates this method for every enum, but it is not declared in Enum.
    It can't be declared in Enum because it is static, and in Enum it would also be abstract (it is not implemented there), but static and abstract are incompatible modifiers.
    Even though we know it will always work, the language has no way to specify that every Enum<E> has that method, and so you can't call it on a type variable.
    As a solution (if you really need this to work), put a Class<E> argument in the constructor, save the Class<E> reference, use reflection on the reference to get values().class A<E extends Enum<E>> {
        Class<E> type;
        A(Class<E> type) { this.type = type; }
        void yourMethod() {
            E[] values=type.getMethod("values").invoke(null);
    }You'll need to deal with a few exceptions but they shouldn't in practice get thrown.
    Bruce

  • Passing general "enum" "class" "thing" :-(

    What I'm trying to do is pass a general enum to a method, like this:
    public void parseEnum(enum toParse)
         for(enum blah : enum.values())
              System.out.println(blah);
    }or whatever (don't care if the stuff inside the method works right now, just threw up an example). I can't do this. Why not? Is there some kind of way I can manage to do this?
    The problem is that I have a whole bunch of enums structured like this:
    enum ListOfElementIds
         ID_ONE( "ThingOne" ),
         ID_TWO( "ThingTwo" ),
         ETC( "ThingThreeOhNoes" ),
         AND_ETC( "ThingFourIsTooMany" );
         private String elementId;
         String getElementId()
              return elementId;
         ListOfElementIds( String elementId )
              this.elementId = elementId;
    }and I'd LIKE to, via a single method, cycle through each of the "values" (ID_ONE would be a value) of any enum I give as a parameter of the method.
    If I'm not explaining this well, please let me know how I can elaborate so as to make my problem as lucid as possible :-P
    (I'm a QA tester writing selenium tests and all the developers that I usually bug about this stuff are OoO :-( )

    import java.lang.reflect.*;
    enum ExampleEnum {HELLO, WORLD};
    public class EnumExample {
        public void iterate(Class<? extends Enum> cls) {
            try {
                Method m = cls.getMethod("values");
                Enum[] values = (Enum[]) m.invoke(null);
                for(Enum e : values) {
                    process(e);
            } catch (NoSuchMethodException exc) {
                exc.printStackTrace();
            } catch (IllegalAccessException exc) {
                exc.printStackTrace();
            } catch (InvocationTargetException exc) {
                exc.printStackTrace();
        public void process(Enum e) {
            System.out.println(e);
        public static void main(String[] args) {
            new EnumExample().iterate(ExampleEnum.class);
    }The values method is static.

  • Advanced enum handling with generics

    Hi everybody,
    i am looking for an optimal solution for my enum issue:
    I got a group of different enums all implementing my Interface XYZ. I create the interface to be sure all enums containing an additional property value
    Here is my problem: Instead of writing a valueForProperty(String property) -method for every enum i have created a method that can be used by all my enums that implements the interface XYZ.
    public Enum<?> valueForProperty(String propertyValue, Enum<? extends XYZ>... enums){
    }- The good thing about this method is, that i can only put enums of type XYZ in it
    - the bad thing is that i have to make a cast when using this method because the return value is only an enum
    IWantThisEnum enum = (IWantThisEnum)this.valueForProperty("thisIsAPropertyValue", IWantThisEnum.values());Has anyone an idea to avoid that cast here?
    Best regards
    Edited by: user8973009 on 14.01.2013 15:23
    Edited by: user8973009 on 14.01.2013 15:23

    user8973009 wrote:
    E extends Enum...why i miss this ... Its not so difficult. Look at the "solution" again (respect to zarr for producing it btw) - sure it works but is it still human readable? Not really! Java (the language) used to be so easy to read, but when you start to over-apply generics it becomes a hard to remember syntactical mess. IMO of course.

  • Generics usage with combined enum & interface class

    I would like to use an enum to store constants for a drop down list, and be able to reuse the structure in a generics method. What I have done is created a interface with basic functionality, and then created an Enum class that implements my interface. Now that I have a single class, I want to pass the resulting class to a static helper function that will have access to the interface functions, and still have the ability to use the benefits of the enum (foreach loops & access to enum constants).
    Is there a way to do this with Generics? I know that this is not right, but maybe it will give an idea of what I am trying to do: <? extends <Enum extends Menu_Interface>>.
    public interface Selection_List {
         public String getName();
         public void setName( String name );
         public String getValue();
         public void setValue( String value );
         public String getGroup();
         public void setGroup( String group );
         boolean isSelected();
    public enum Tool_Types implements Selection_List
         SAMPLE_ONE( "name1", "value1" ),
         SAMPLE_TWO( "name2", "value2" );
         // ... implementation of interface functions
    public class FormGenerator
         public static <T extends <Enum extends Selection_List>>
              String doCreateDropDown( T selectionList )
              //  ... implementation of function
    };

    You surely can. The following is an example on implementing Runnable:
    public class EnumWithInterface {
        enum Days implements Runnable {
         MON, TUE, WED, THU, FRI, SAT, SUN;
         @Override
         public void run() {
             System.out.println("Running " + this);
        static <E extends Enum<E> & Runnable> void runAll(Class<E> runnableEnum) {
         for (E e : runnableEnum.getEnumConstants()) {
             e.run();
        public static void main(String[] args) {
         runAll(Days.class);
    }

Maybe you are looking for

  • Vendor Master:  Name, Street Address and PO Address

    Hello SAP Gurus- I am working on a Vendor Master cleanup hopefully to streamline our Vendor Master Data.  We have data in all fields of the vendor master for address and in effort to decide on what to do with the SAPScript for checks, we would like t

  • Save Digital Data to a Text File

    I have digital data collected from two ports simultaneously as N number of samples in waveform that I do calculations on to get a result. I would like to save the raw data in a text file so that it can be easily viewed in an external program, like Ex

  • Can't open a Word document

    I've been sent some word documents via email and I can't open them. My computer says that Word 2010 is not installed on my computer. It is. It came with my computer. This makes no sense. Can anyone offer an explanation?

  • I can't open my photo's in Bridge because the camera (Canon EOS D650) RAW file is not recognized?

    Ik kan in Bridge mijn foto's via photodownloader niet openen omdat RAW bestand van camera (Canon EOS 650D) niet ondersteund wordt, ook niet na updates?

  • Which computer should I get?

    Hello, I'm setting up to make my first independent movie, and I'm planning on using an Apple instead of a PC. So, my question is -- because I'm new to the Apple World -- should I go with a MacBook Pro or a G5? Also, I'm using the Panasonic HVX-200. T