Java枚举扩展了解决方法

时间:2013-10-03 09:21:19

标签: java inheritance enums

有没有比这更好的“解决方法”?我想在访问TableMap上的方法时避免使用PREFIX(local var)。

public class TableMap extends TreeMap<String, String> {
    public String field1, field2, field3;
    public TableMap(Tables table){}
    public void method(){}
    public void method2(){}
    public void method3(){}
    ...
}

的解决方法!

public enum Tables {
    table1, table2, table3;
    public final TableMap MAP=new TableMap(this);
    private Tables(){}
}

需要!

public enum Tables extends TableMap {
    table1, table2, table3;
    public Tables(){
        super(table);
    }
}

整个代码示例:

    // workaround!
    Tables.table1.MAP.method();
    Tables.table2.MAP.method();
    Tables.table3.MAP.method();
    ...

    // needed!
    Tables.table1.method();
    Tables.table2.method();
    Tables.table3.method();
    ...

2 个答案:

答案 0 :(得分:3)

在Java中,enum类型必须扩展java.lang.Enum。由于Java类型只能扩展单个类型,您可能认为public class TableMap extends Enum可能有效,但不是,编译器不会允许这样做。

在我自己的代码中,我经常使用enum作为密钥,因为它们非常恶劣。我让他们实现了一个通用接口,然后使用工厂来查找&#34; worker&#34;的特定实现。我可以使用的实例。

更接近所需语法的一种方法是使用委托模式:

public enum Tables {
    ...
    public void method() {
        MAP.method();
    }
}

答案 1 :(得分:2)

我认为你可能试图将过多的情报放入enum

我发现这种方法非常有用。它避免了许多问题,因为你无法扩展enum s(实际上你可以但不能以非常有用的方式扩展)。

基本上,将enum作为子类,并将其特征作为EnumSet传递给超类。这样,您仍然可以获得enums的所有好处,包括类型安全。

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) {
  }

}

您甚至可以使用EnumMap代替TreeMap来提高效率。