开发者

Java Interface to enforce definition of enum type

开发者 https://www.devze.com 2023-03-11 21:29 出处:网络
I need to define an Interface that redefines something like a hashset. So I have methods to of the type get(byte key). As I can not use descriptive keys like String I am looking for a generic way to

I need to define an Interface that redefines something like a hashset.

So I have methods to of the type get(byte key). As I can not use descriptive keys like String I am looking for a generic way to define the keys available within some implementation of the interface. I think of using an enum for that. But is it possible to force the definition of such Enum within the Interface?

To make clear what I mean lets look on an example class implementing the Interface:

public class ByteHashsetImpl implements ByteHashset {
    public enum Key {
        STATE_A,
        STATE_B,
        STATE_C;
    }

    public enum Value {
        VALUE_A,
        VALUE_B,
        VALUE_C;
    }

    public void get(Key k) {
        /**/
    }

}

I want to ensure that each implementation defines and uses 开发者_运维知识库its own Enums called Key and Value. This would make it possible to access the key/values using something like ByteHashsetImpl.Key for every implementation of the interface.

Is it possible at all or is there another option beside an informal definition like coding quideline?


You can't enforce the creation of such enums, but you can force a type argument to be an enum:

public interface Frobnicator<E extends Enum<E>> {
  void frobnicate(E value);
}


enum Bar {
  X, Y;
}

class BarFrobnicator implements Frobnicator<Bar> {
  @Override
  public void frobnicate(Bar value) {
    // do stuff
  }
}

In this case a Frobnicator could simply re-use an existing enum class, but E in Frobnicator will always be an enum type.


As suggested by Joachim Sauer, you can have Enum type arguments:

public interface MyMap<K extends Enum<K>, V extends Enum<V>> {

    public V get(K key);

}

Then you can have:

public enum StateKeys {

    STATE_A,
    STATE_B,
    STATE_C;

}

and

public enum StateValues {

    VALUE_A,
    VALUE_B,
    VALUE_C;

}

and finally

public class MyStateMap implements MyMap<StateKeys, StateValues> {

    @Override
    public StateValues get(StateKeys key) {
        if (key == StateKeys.STATE_A)
            return StateValues.VALUE_A;
        else if (key == StateKeys.STATE_B)
            return StateValues.VALUE_B;
        else if (key == StateKeys.STATE_C)
            return StateValues.VALUE_C;
        else
            throw new IllegalArgumentException("illegal key " + key);
    }

}
0

精彩评论

暂无评论...
验证码 换一张
取 消