I am currently at a stage in my project where I have a bunch of classes which all sub class one abstract class.
My program asks for input from the user and the way that I want to be able to create objects from these classes is by somehow using the input.
The input is exactly the same as the Class names, for example (if they were to enter "Test" then I would want to create a Test class or if they were to enter "Blah" then I would want to create a Blah class and these two classes as well as all the other classes would subclass one main abstract class.
I am just wondering how I would go about creating these instances of these subclasses from just the input.
Try it by using Class.forName():
public class Example {
public static void main(String[] args) throws Exception {
Example example = (Example) Class.forName("Example").newInstance();
example.printMe();
}
public void printMe() {
System.out.println("Hallo");
}
}
You may have to add your package name, if the classes are not entered with package names and they are not defined in the default package. Perhaps you have to use something else then the default constructor. To few infos so. Its just an example. Hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With