ClassLoad an Enum type

主宰稳场 提交于 2019-12-05 02:27:47

To expand on my comment, I think the cleanest you'll 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 the unchecked cast from Class<?> to a proper enum type. But at least the @SuppressWarnings is limited in scope.


Edit:

Upon further checking, there is actually a simpler way of achieving what you need, without needing to know the name of an instance and without warnings:

Class<?> containerClass = loader.loadClass("com.somepackage.app.Name");
containerClass.getEnumConstants()

Loading an enum doesn't cause it to initialize. You have to reference it through either a field reference or a method reference. So even a simple statement like Name name = Name.SERVER; or Name.SERVER.name(); would do the trick.

See section 5.5 Initialization in chapter 5. Loading, Linking, and Initializing of the Java Virtual Machine Specification.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!