I have an interface Moded
. The methods are getMode()
, setMode( Enum<?> mode )
.
It also has a method getMode( Object key )
, which is used to identify the "mode type" in implementing classes when they have multiple modes (e.g. OPEN/CLOSED is one state, but COMMAND_MODE/QUERY_MODE/OTHER_MODE is another state, i.e. "2 dimensions" of mode).
The implementing classes will then use enums
to provide the possible values of each mode type.
The idea is that getMode( Object key )
is passed a key which the implementing class uses to identify the mode type to find the value of. But to make this nicer it would be ideal if you always had to use the Enum
class object as the key. You can do this anyway, but to enforce it, I've tried changing to getMode( Class<Enum<?>> key )
.
For some reason, say I have a class IndexManager
which implements Moded
, and it contains an enum
like this:
enum MANAGER_MODE {
COMMAND_MODE, QUERY_MODE, OTHER_MODE
}
and my implemented method looks something like this:
@Override
public Enum<?> getMode(Class<Enum<?>> key ) throws Exception {
if( key.equals( IndexManager.MANAGER_MODE.class )){
return managerMode;
}
...
... and I then try this:
indexManager.getMode( IndexManager.MANAGER_MODE.class )
I'm getting a message in Eclipse
The method getMode(Class<Enum<?>>) in the type IndexManager is not applicable for the arguments (Class<IndexManager.MANAGER_MODE>)
And yet this says "true":
String.format( "extends Enum? %s", Enum.class.isAssignableFrom( IndexManager.INDEX_MANAGER_MODE.class ))
Later
In fact the answer by Andreas is better (no casting; type safety if required). Using his approach you put
<T extends Enum<T>> T getMode(Class<T> key )
to allow implementation of multi-mode classes
and
<T extends Enum<T>> T getMode()
to allow implementation of single-mode classes