gpt4 book ai didi

java - 如何在运行时调用方法的方法?

转载 作者:行者123 更新时间:2023-11-30 05:56:23 25 4
gpt4 key购买 nike

我知道使用反射我们可以在运行时调用方法。我有一个要求obj.getMethod1().getMethod2().getMethod3()在运行时调用。方法名称只有在运行时才知道。运行时方法的数量也有所不同。有时可能是obj.getMethod1().getMethod2() .

目前我正在通过数组进行处理,如下所示

 obj=initialObj;
for(i=0;i<arrayValue.length;i++){
tempobj=obj.getClass.getMethod(arrayValue[i])// arrayValue contains method name
obj=tempobj;
}

还有其他更好的方法吗?

最佳答案

假设您的方法没有参数,您可以这样做:

public static Object callChainedMethods(Object obj, String[] methodNames) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Class<?> type = obj.getClass();
Object objectOnWhichToCallMethod = obj;
for (String methodName : methodNames) {
Method m = type.getMethod(methodName);
objectOnWhichToCallMethod = m.invoke(objectOnWhichToCallMethod);
type = objectOnWhichToCallMethod.getClass();
}
return objectOnWhichToCallMethod;
}

如果不需要返回最终的返回值:

public static void callChainedMethods(Object obj, String[] methodNames) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Class<?> type = obj.getClass();
Object objectOnWhichToCallMethod = obj;
for (String methodName : methodNames) {
Method m = type.getMethod(methodName);
objectOnWhichToCallMethod = m.invoke(objectOnWhichToCallMethod);
type = objectOnWhichToCallMethod.getClass();
}
}

例如:

String[] methods = {"toString", "getClass", "getClass"};
System.out.println(callChainedMethods((Integer)10, methods));
// prints "class java.lang.Class"
// because it is calling ((Integer)10).toString().getClass().getClass()

关于java - 如何在运行时调用方法的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53096515/

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