【问题标题】:How to call a method in another class when the given classname is string当给定的类名是字符串时如何调用另一个类中的方法
【发布时间】:2019-08-04 10:12:42
【问题描述】:

我在 java 中有两个类。当第二类名称存储在字符串变量中时,我正在从第一类调用第二类的方法。 我尝试了下面的代码。它创建了类。

String adapterClass = "com.appzillon.server.impl.ViewAccDtlsAdapterImpl";
Class className = Class.forName(adapterClass);

然后如何调用方法。方法名称为getInfo,带有字符串类型参数。

【问题讨论】:

    标签: java class object methods dynamic


    【解决方案1】:
    Method method = className.getDeclaredMethod("getInfo", String.class);
    method.invoke(instance, "your parameter");
    

    instance 是:

    Object instance = null;
    

    如果方法是静态的。或者:

    Object instance = className.getDeclaredConstructor().newInstance();
    

    如果方法是成员方法

    【讨论】:

    • 在实例声明行出现以下错误。此行有多个标记 - 未处理的异常类型 NoSuchMethodException - 未处理的异常类型 InvocationTargetException - 未处理的异常类型 InstantiationException - 未处理的异常类型 IllegalAccessException
    • @VinodhaSamiraja 你必须try-catch 这些异常或在方法级别使用throws 声明
    【解决方案2】:

    对于这样的场景,您可以很好地使用 Java 反射 API。 Class classInstance = Class.forName(<your class name>); Methoed methodHandle = classInstance.getMethod(<methodName>,<arguments classes>); Object returnValue = methodHandle.invoke(null, "parameter-value1");

    注意:null 参数是您要对其调用方法的对象。如果方法是静态的,则提供 null 而不是对象实例

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-23
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多