i would like to get rid of these warnings about unchecked conversion and parameterization without surpressing them.
interface Switch {
void toggle();
}
enum A implements Switch {
a1,a2;
@Override public void toggle() {
state=!state;
}
boolean state;
}
enum B implements Switch {
b1,b2;
@Override public void toggle() {
state=!state;
}
boolean state;
}
public class Warnings {
public static void main(String[] args) {
Class<? extends Enum>[] enums=new Class[]{A.class,B.class};
for(Class<? extends Enum> clazz:enums)
try {
Enum s=Enum.valueOf(clazz,args[0]);
((Switch)s).toggle();
} catch(IllegalArgumentException eee) {}
}
}
You can’t without writing your own
valueOf.Enumis defined as:and
Enum.valueOfis defined as:Note the recursive type parameterization which implies that you can only call
valueOfwith a specific enum class (e.g.A.class), but not with a generic one, as aClass<? extends Enum<?>>is not a match because the two question marks aren’t assumed to represent the same (unknown) type by the compiler.So apart from using generic collections instead of arrays, you have to write your own
valueOfmethod that accepts any enum class.