jeudi 18 juin 2015

Java way to create an object based on enum type

My class is like this:

class X {}
class Y extends X {};
class Z extends X {};

I have an enum for each subclass (id + class):

enum Type {
   Y_TYPE(1, Y.class), Z_TYPE(2, Z.class);
   int id;
   Class c;
   public Type(int id, Class c) { this.id = id; this.c = c; }
   public static X createInstance() throws Exception {
      return c.newInstance();
   }
}

Then I used them as follows:

X parseFromID(int id) {
   for (Type v : Type.values()) {
     if (v.id == id) {
        return v.createInstance();
     }
   }
}

It works fine but I'm wondering if this a Java-ist way to create data based on integer id ? Is there any bad thing that should look for ?

Is there a way to enforce the class that is passed into are of X type without lengthy if-else condition? Think when I have a large number of subclasses.


Why do you want to work on integer ids?

I'm writing some sort of parser, so I need to convert integer id that I've taken from somewhere to the appropriate object.

Aucun commentaire:

Enregistrer un commentaire