I have a Forum
class with some subclasses, and I store the subclass name as a String field on a database along all other fields. When I retrieve the object, I want it to be an instance of the same class it was. I could do a lot of if-else statements to find which subclass constructor to call, but it wouldn't be easily extensible.
I have found this solution, but it feels somehow dirty:
public static Forum createForum(int forumId, String kind) {
try {
Class cls = Class.forName("forum."+kind);
Constructor ct = cls.getConstructor(Integer.TYPE, String.class);
Object retobj = ct.newInstance(forumId, kind);
return (Forum) retobj;
}
catch (Throwable e) {
System.err.println(e);
}
return null;
}
Is there any better solution?
Thanks.