To expand on my comment, I think the cleanest thing you get is something like this:
public static <T extends Enum<T>> T loadEnum(ClassLoader loader, String classBinaryName, String instanceName) throws ClassNotFoundException { @SuppressWarnings("unchecked") Class<T> eClass = (Class<T>)loader.loadClass(classBinaryName); return Enum.valueOf(eClass, instanceName); }
There is really no way to avoid an uncontrolled cast from Class<?> the correct enum type. But at least @SuppressWarnings limited in scope.
Edit:
Upon further verification, there is actually an easier way to achieve what you need, without having to know the instance name and without warning:
Class<?> containerClass = loader.loadClass("com.somepackage.app.Name"); containerClass.getEnumConstants()
Realskeptic
source share