You need to pass the actual enum class object as a parameter to your method. Then you can get the enum values using Class.getEnumConstants()
.
In order to be able to access getCode()
on the instances, you should define it in an interface and make all your enum types implement that interface:
interface Encodable {
Integer getCode();
}
public static <T extends Enum<T> & Encodable> T getValueOf(Class<T> enumClass, Integer code) {
for (T e : enumClass.getEnumConstants()) {
if (e.getCode().equals(code)) {
return e;
}
}
throw new IllegalArgumentException("No enum const " + enumClass.getName() + " for code \'" + code
+ "\'");
}
...
public enum MyEnum implements Encodable {
...
}
MyEnum e = getValueOf(MyEnum.class, 10);