I have a parent class and 2 child classes. I am trying to implement a function that accepts a type of a child, and which child - as parameters.
When I use child.newInstance(), I want to save it in a variable of a passed type and call the function from the second parameter.
The following are the classes
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");
}
}
and here is the method I'm trying to implement
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
}
}
Can I do what I'm trying to do? If so, how can I pass this object to the type that was passed?
source
share