For example, I have a class A, A has a child class B and C, I want to create A, B or C randomly, I can use conditional statements like this:
A a;
switch(new java.util.Random(3).nextInt()){
case 0:
a=new A();
break;
case 1:
a=new B();
break;
case 2:
a=new C();
break;
}
a.doSomething();
but I want to have a better version of support that easily adds a new child class, and then I try to use an array to store the .class object for each class, but it cannot compile due to "incompatible types":
Class[] array={A.class,B.class,C.class};
A a;
try{
a=array[new java.util.Random(array.length).nextInt()].newInstance();
}catch(Exception e){
}
a.doSomething();
is there syntax to solve the problem above? If not, is there any general way or syntax that can generate a random child without an if-else condition?