i need to create an object according to user input, that is to say: there are several predefined classes: a_Class, b_Class, c_Class, they are all PreClass type. if user input a_Class, i instance an object as a_Class type, however, if user input d_Class, because it does belong to PreClass type, hence an exception will be thrown out. how can i achieve this, how can i convert user input string value into PreClass type. "if" statement should not be used here because there are tens of subclasses of PreClass Cheers
Hi, Welcome to JavaRanch! Please don't post your questions to more than one forum. I deleted the other copy of this post over in the beginner's forum. The static method forName() in the java.lang.Class class will return the Class object that represents a class, given its name as a String; then you can call newInstance() on the Class object to construct an instance of the class. So String name = "a_class"; Class c = Class.forName(name); PreClass p = (PreClass) c.newInstance(); will do what you want (assuming the named class has a no-argument constructor.) If "name" isn't the name of a subclass of PreClass, you'll get a ClassCastException.
Otherwise, this is a perfect example of when to use the factory pattern. Essentially, you do have a big "if" statement (or similar) but you encapsulate the ugliness inside one class (or method if you'd rather, that would be a warped form of the pattern). So, you might have a class like this:
This is more work than the above solution if all classes have a no-arg constructor. However it's more flexible - if you need to perform different actions during creation depending on the subclass, you can simply alter the action in the if statement. Anyway, that's another idea. Googling for 'factory pattern' will probably lead to more info. Cheers,
--Tim [ April 05, 2004: Message edited by: Tim West ]
Class c = Class.forName(name); will not work if the class to be reloaded is outside the classpath and not in the same directory as the initiator class. A possible solution is using the URLClassLoader and here is an example:
author and iconoclast
"Redragon" -- When I posted my earlier reply, your display name conformed to the JavaRanch naming policy, but now it does not. Please read the linked document, then change it back, pronto! [ April 06, 2004: Message edited by: Ernest Friedman-Hill ]