Load class for type Enum

How can I create an instance of an Enum type using ClassLoader or a similar mechanism? (I'm trying to save everything under the same class loader for a stand-alone server application).

I have something like:

ClassLoader loader = new CustomClassLoader(parent, libDir); Thread.currentThread().setContextClassLoader(loader); // trouble area Class<?> containerClass = loader.loadClass("com.somepackage.app.Name$SERVER"); 

I mistakenly thought that just loading Enum would be enough to drop it (the private constructor contains invocation method calls and no).

Doing what I have above does not lead to any exceptions, but the JVM just ends after the last line and the server does not start.

Obviously what to do:

 containerClass.newInstance(); 

Exclusion Results.

+8
java enums classloader
source share
2 answers

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() 
+4
source share

Downloading an enumeration does not cause its initialization. You must reference it through a link to a field or a link to a method. Therefore, even a simple statement like Name name = Name.SERVER; or Name.SERVER.name(); will do the trick.

See section 5.5 Initialization in Chapter 5. Downloading, linking, and initializing the Java Virtual Machine specification.

0
source share

All Articles