将对象强制转换为作为参数传递的类类型
我有一个家长班和2个子班。我正在尝试实现一个函数,该函数将子项的类型和哪个子项作为参数。
当我使用 时,我想将其存储在传递类型的变量中,并从第二个参数调用函数。child.newInstance()
以下是课程
public class Parent {
    public void test() {
        System.out.println("Test from parent");
    }
}
public class ChildA extends Parent {
    public void testChildA() {
        System.out.println("Test from child a");
    }
}
public class ChildB extends Parent {
    public void testChildB() {
        System.out.println("Test from child b");
    }
}
这是我试图实现的方法
public class Driver {
    Parent func(Class child, String whichChild) throws Exception {
        // whichChild: "ChildA" or "ChildB"
        Object obj = child.newInstance();
        // cast obj to type of child and call the method "test" and "test" + whichChild
    }
}
它能做到我想要做的事吗?如果是,如何将此对象强制转换为传递的类型?
 
					 
				 
				    		 
				    		 
				    		 
				    		