I am working on a java application. The is an abstract class Model and 2 derived classes Model 1 and Model 2. Model1 and Model2 behave differently, so I want to allow the user to select a model from the two.
It can be implemented like:
Model model;
If(response==1){
model = new Model1();
}else if(response==2){
model = new Model2();
}
Now the problem with this is, that if I add a new class Model3, I have to rewrite the code.
I could create a List, where I would add an instance from each class, then I would add a static method, that would return a new Instance of the class, but I hope it can be done with bit a more style.
Is there possible to create a List, to hold the type of each class. From this List I could create a menu to select a model, and then use the type to create the class the user needs.
So is it possible, to create a List<Class>, then use the Class object as a constructor, to create an instance of the given class?
You can create a list of suppliers:
You could muck around with reflection, but that requires stepping outside Java’s normal exception handling mechanisms, requires zero-argument
publicconstructors andpublicclasses which limits how code can change under maintenance in ways that aren’t checked byjavac, and just isn’t necessary in this case.