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.
There is really no reason to use reflection here. Throwing Exception is also a bad practice, and if you didn't use reflection, you wouldn't have to deal with reflection exceptions. You could simply do
This is also helpful because it doesn't force every subclass to have a public no-arg constructor, and also allows returning the same instance of X or Y, if possible.
If you're concerned about the verbosity of the anonymous class definitions, you could replace them with lambdas, if you're using Java 8: