如果类名作为字符串传递,如何动态调用类的方法

问题描述

我想创建动态对象,以便我调用该类的相应方法。所有的类和接口都在不同的文件中,但在同一个文件夹下 鉴于:

interface Method
{
    public void display();
}
class Car implements Method
{
     public void display()
     {
       System.out.print("Car method");
     }
}
class Honda implements Method
{
     public void display()
     {
       System.out.print("Honda method");
     }
}

public class Main {

public static void main(String[] args) throws ClassNotFoundException,InstantiationException,illegalaccessexception,NoSuchMethodException,InvocationTargetException {
    String className = "Car";
    Class cls = Class.forName(className);
    Method method = (Method) cls.getConstructor().newInstance();
    method.display();
  }
}

现在,如果在字符串中传递本田,那么我想调用字符串方法,但是如果我在字符串中传递 Car ,那么我想获取 Car 方法作为输出,但是在编译之后,不会调用方法。没有错误,但也没有预期的输出。如何获得所需的输出。请帮忙。

解决方法

您可以调用所需的方法。

Method method = cls.getMethod("display");
method.invoke(parameters);

如果我被允许更新上面的代码,它会像下面这样,

interface Car
{
    public void display();
}
class Honda implements Car
{
     public void display()
     {
       System.out.print("Car method");
     }
}

public class Main {

public static void main(String[] args) throws ClassNotFoundException,InstantiationException,IllegalAccessException,NoSuchMethodException,InvocationTargetException {
    String className = "Car";
    Class cls = Class.forName(className);
    Honda honda = (Honda)cls.newInstance()
    honda.display();
}
}

希望这会清除我在上面的答案中提到的 Method 类的事情。

,

方法 class.newInstance() 已被弃用。所以你应该使用

Class<?> clazz = Class.forName(className);
Constructor<?> ctor = clazz.getConstructor(String.class).newInstance();
Object object = ctor.newInstance(ctorArgument);

SN:在这种情况下,我假设构造函数只有一个 String 参数值。必须调用 getConstructor 方法,传递所需构造函数具有的所有类类型(正确排序)。 使用 newInstance 时,您需要传递实际构造函数的参数值

此时您必须使用 getMethod() 获取方法,它需要方法名称和所有参数的类型。要实际调用该方法,您需要传递要调用该方法的对象的实例(在本例中为我们的 对象 并传递实际参数的值以使用

clazz.getMethod("methodName",String.class,String.class).invoke(object,"parameter1","parameter2");

EDIT:OP 更新了由两个类实现通用接口的问题。在这种情况下,您实际上可以调用您知道每个类都将实现该接口的方法。这样你就不必使用任何反射魔法,除了创建对象本身的新实例

使用通用接口

Method method = (Method) Class.forName(className).getConstructor().newInstance();
method.display();

最后一行将调用实现接口的对象实例的显示方法