Is it possible to create a random object with the same parent class without conditional statements?

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?

+4
3

, . , List, .

List<Class<? extends Number>> list = Arrays.asList(Number.class, Double.class, Integer.class);
try {
    Number a=list.get(new Random().nextInt(list.size())).newInstance();
}catch(Exception e){
}

Class<? extends Number>[], .

+3

java 8

    interface Sup extends Supplier<A>{}

    Sup[] sup = { A::new, B::new, C::new };

    A a = sup[rand].get();

    Supplier<A>[] sup = array( A::new, B::new, C::new );


    @SafeVarargs
    public static <T> T[] array(T... args){ return args; }
+2

Class <? A > [], ?

, .

() , , . Vector, .

-1

Source: https://habr.com/ru/post/1608610/


All Articles