Ogen Ogen - 1 year ago 89
Java Question

Enforcing the implementer of an interface to be an enum

I would like to store a type called

inside a set.
needs to be an enum that implements the

Set<App> myApps;

I have defined the interface like so...

interface App<T extends Enum<T>> {}

This is almost working, for example, you cannot do this...

class MyClass implements Application<MyClass> {}

However, you can do this...

enum MyEnum implements Application<MyEnum> {}
class Myclass implements Application<MyEnum> {}

Which is wrong. I only want enums to be able to implements this interface, how can I enforce this?

Answer Source

Define a method that allows you to add Elements into the set, BUT use a constraint for that parameter...

 public <E extends Enum<E> & IMyInterface> void addToSet(final E value) { }

now after that

addToSet(MyEnum.K) will compile


addToSet(new Myclass()) will NOT compile
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download