I was wondering if there was a way to instantiate a class from the value of a string. Here's an example:
There is a main class that prompts the user for a string. Say the user enters "Hello". Assuming Hello is an instantiable class, is there a way for the main class to take that string and create a Hello object?
Also, assume that there are too many classes defined that the user might type in for a switch case statement to be feasable or reliable.
If anything is unclear, please ask. Thanks for the help!
Campbell Ritchie wrote:I think you can only instantiate classes like that if they have a no-arguments constructor.
If you need to create an instance of a class that doesn't have a no-argument constructor, you can use the several "getConstructors()" methods of java.lang.Class to allow you to call any other constructor.