marcolopes
marcolopes

Reputation: 9288

Java enum extends workaround

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 extends TreeMap<String, String> {
    public String field1, field2, field3;
    public TableMap(Tables table){}
    public void method(){}
    public void method2(){}
    public void method3(){}
    ...
}

workaround!

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

needed!

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

Example throughout the code:

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

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

Upvotes: 0

Views: 7455

Answers (2)

OldCurmudgeon
OldCurmudgeon

Reputation: 65889

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.

Upvotes: 2

Aaron Digulla
Aaron Digulla

Reputation: 328870

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();
    }
}

Upvotes: 3

Related Questions