简体   繁体   中英

Get reference to Java Enum that implements an interface from enum class name

I want to implement a basic state machine using enums; the enums implement an interface to manage allowed state transitions. But I want to configure in a property file a list of class names of enums that implement the interface and should be used in a particular context. The context is determined at runtime, and that context key maps to a property key in the properties file. Once I get the class name of the enum for a context from the properties file, how can I use that class name to get an instance reference to use that enum via the interface methods? I can see that you can use reflection to discover a particular enum's attributes but that's it. Any ideas?

You're right about using reflection:

  1. Use Class.forName to get the proper Class object once you've read the class name from your properties file. Make sure you pass in the fully qualified class name. You'll need to catch various checked exceptions here.

  2. Make sure it's an enum that implements your interface, with the isEnum method and using the isAssignableFrom method from your interface's Class object.

    isEnum() && YourInterface.class.isAssignableFrom(clazz)

  3. Use the static Enum.valueOf method to get the actual enum constant from a String and cast it to your interface.

     (YourInterface) Enum.valueOf(clazz, stringName) 

I wrote this... it may help you:

public class MyTests {

  static enum XX implements Runnable {
    A, B;
    public void run() {
      System.out.println( "I'm enum value: " + this.name() );
    }
  }

  public static void main( String[] args ) throws Exception {
    new MyTests();
  }

  public MyTests() throws Exception {
    Class<?> loaded = Class.forName("MyTests$XX");
    Class<? extends Runnable> xx = loaded.asSubclass(Runnable.class);
    Runnable[] enumConstants = xx.getEnumConstants();
    for ( Runnable runnable : enumConstants ) {
      runnable.run();
    }
  }

}

This will print:

I'm enum value: A
I'm enum value: B

Yeah.

Don't softcode that stuff, unless you really really really need to.

http://thedailywtf.com/Articles/Soft_Coding.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM