gpt4 book ai didi

java - 使用反射动态调用方法

转载 作者:行者123 更新时间:2023-12-02 00:13:58 24 4
gpt4 key购买 nike

我想编写一个程序来决定在运行时调用对象的哪些方法。

例如

 <method>getXyz<operation>
<arg type="int"> 1 <arg>
<arg type="float"> 1/0 <arg>

现在我在 XML 文件中有类似上面的内容,我想决定在运行时调用哪个方法。方法可以有多种。

我不想在我的代码中执行如下操作:

 if (methodNam.equals("getXyz"))
//call obj.getXyz()

如何使用 Java 反射来做到这一点?

我还想在运行时构造参数列表。例如,一种方法可以采用2 个参数,另一个可以采用 n 个参数。

最佳答案

您应该使用 Object.getClass() 获取 Class 的方法首先对象。

那么你应该使用 Class.getMethod() Class.getDeclaredMethod() 获取 Method ,最后使用 Method.invoke() 调用此方法。

示例:

public class Tryout {
public void foo(Integer x) {
System.out.println("foo " + x);
}
public static void main(String[] args) throws Exception {
Tryout myObject = new Tryout();
Class<?> cl = myObject.getClass();
Method m = cl.getMethod("foo", Integer.class);
m.invoke(myObject, 5);
}
}

Also i want to construct the parameter list at runtime.For Example one method can take 2 parameters and other can take n args

这不是问题,只需创建 Class<?>数组即可对于参数的类型,以及 Object 的数组参数值的 s,并将它们传递给 getMethod()invoke() 。它之所以有效,是因为这些方法接受 Class<?>...作为参数,并且一个数组适合它。

关于java - 使用反射动态调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12234439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com