Java enum extends workaround

后端 未结 2 1387
-上瘾入骨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> extends TreeMap {
      public MappedEnum(EnumSet e) {
        // Whatever you like with the set.
      }
    
      public void method(E e) {
      }
    
    }
    
    public static class Foo extends MappedEnum {
      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.

提交回复
热议问题