Java enum extends workaround

后端 未结 2 1386
-上瘾入骨i
-上瘾入骨i 2021-01-17 07:17

Is there a better \"workaround\" than this? I want to avoid the use of a PREFIX (local var) when accessing the methods on TableMap.

public class TableMap ext         


        
相关标签:
2条回答
  • 2021-01-17 07:40

    I think you may be trying to put too much intelligence into the enum.

    I have found this approach very useful. It avoids many of the issues arising from the fact that you cannot extend enums (well actually you can but not in a very useful way).

    Essentially, make the enum a sub-class and pass its characteristics up to your super class as an EnumSet. This way you still get all the benefits of enums including type safety.

    public static class MappedEnum<E extends Enum<E>> extends TreeMap<String, String> {
      public MappedEnum(EnumSet<E> e) {
        // Whatever you like with the set.
      }
    
      public void method(E e) {
      }
    
    }
    
    public static class Foo extends MappedEnum<Foo.Tables> {
      public enum Tables {
        table1, table2, table3;
      }
    
      public Foo() {
        super(EnumSet.allOf(Tables.class));
      }
    
      @Override
      public void method(Foo.Tables e) {
      }
    
    }
    

    You could probably even use an EnumMap instead of your TreeMap for better efficiency.

    0 讨论(0)
  • 2021-01-17 07:41

    In Java, enum types must extend java.lang.Enum. Since Java types can every only extend a single type, you might think that public class TableMap extends Enum might work, but no, the compiler won't allow this.

    In my own code, I use enums often as mere keys because they are so hostile. I have them implement a common interface and then use a factory to look up specific implementations of "worker" instances that I can then use.

    One way to get closer to the syntax that you want is to use the delegate pattern:

    public enum Tables {
        ...
        public void method() {
            MAP.method();
        }
    }
    
    0 讨论(0)
提交回复
热议问题