Enforcing an interface interface for enumeration

I would like to save a type called App inside the set. App must be an enumeration that implements the App interface.

 Set<App> myApps; 

I defined the interface like this ...

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

It almost works, for example, you cannot do this ...

 class MyClass implements Application<MyClass> {} 

However, you can do it ...

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

It is not right. I just want the enums to implement this interface, how can I provide this?

+7
java enums interface
source share
2 answers

Define a method that allows you to add items to the set, BUT use the restriction for this parameter ...

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

now after that

 addToSet(MyEnum.K) will compile 

but

 addToSet(new Myclass()) will NOT compile 
+11
source share

AFAIK it is not possible to provide an implementation of an interface interface in order to have certain properties, such as an enumeration.

However, depending on your code and how you use this interface, you can make it difficult to prevent someone from listing the developer:

  • Require T implement App<T> to prevent any enum from being passed to the class declaration (i.e. App<T extends Enum<T> & App<T>> )
  • Use extra boundaries when possible (see ΦXocę 웃 Pepeúpa answer)
  • Add methods that are already implemented with Enum , such as name() , ordinal() , getDeclaringClass() , etc.
  • Let App<T ...> extend Comparable<T> .
  • When possible, call getClass().isEnum() to check this property at runtime. This is not ideal, but there is a similar solution that is commonly used, for example Collections.unmodifiableSet() .
+1
source share

All Articles