Passing an object to a class passed as a parameter

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?

+4
source share
4 answers

If you add a restriction on child, you do not need to throw to get the parent element:

Parent func(Class<? extends Parent> child, String whichChild) throws Exception {
    // whichChild: "ChildA" or "ChildB"

    Parent obj = child.newInstance();
    //...
}

- testChildA etc, , , Parent. , :

Method method = obj.getClass().getMethod().getMethod("test" + whichChild);
method.invoke(obj);

Parent, , .

public abstract class Parent {
  public void test() {
    System.out.println("Test from parent");
  }

  public abstract void testChild();
}

:

obj.testChild();

, , test ChildA ChildB .

+5

, , Class.cast(...).

,

public <T> T getInstance(Class<T> type) {
    Object o = type.newInstance();
    T t = type.cast(o);
    return t;
}
+6

.

public class Driver {
    Parent func(Class child, String whichChild) throws Exception {
        // whichChild: "ChildA" or "ChildB"

        child.forName(whichChild);

        Object obj = child.newInstance();
        // cast obj to type of child and call the method "test" + whichChild
    }
}
0

. , .

So, for the compiler, there is no evidence that this instance is actually an instance of the type you are sending.

-1
source

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


All Articles