gpt4 book ai didi

java - 如何使用反射设置数组

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:28:43 27 4
gpt4 key购买 nike

我有一个类,其中有这样的 setter 和 getter

private String[] message;

public String[] getMessage() {
return message;
}

public void setMessage(String[] message) {
this.message = message;
}

现在我正在尝试使用像这样的反射来调用 setter

private static String[] getMessageArray(int traineeIndex) {
....
String[] messageArray = new String[nodesLength];

for (int i = 0; i < nodesLength; i++) {
...
messageArray[i] = nodeValue;
}
return messageArray;
} //end of getMessageArray()

private static void doProcessedStuff() {
...
for (int i=1; i<=count ; i++) {

Object myClassInstance = dynamicClassLoading(packageName, className);
...
String[] messageArray = getMessageArray(i);
printXpathResult(myClassInstance, result, messageArray);
}
} //end of doProcessedStuff()

public static void printXpathResult(Object myClassInstance, Object result, String[] messageArray){
...
String methodName = methodPrefix + nodeName; //setMessage
invokeMethodDynamically(myClass, myClassInstance, methodName, null, messageArray);
} //end of printXpathResult()

private static void invokeMethodDynamically(Class<?> myClass, Object myClassInstance, String methodName,
String methodParameter, String[] messageArray) {
...
if (messageArray != null) {
myMethod = myClass.getMethod(methodName, new Class[] { Array.class });
String returnValue = (String) myMethod.invoke(myClassInstance, messageArray);

} else {
myMethod = myClass.getMethod(methodName, new Class[] { String.class });
String returnValue = (String) myMethod.invoke(myClassInstance, new String(methodParameter));
}
} //end of invokeMethodDynamically().

但是当我排队的时候

myMethod = myClass.getMethod(methodName, new Class[] { Array.class });

我收到以下错误

java.lang.NoSuchMethodException: 
pk.training.basitMahmood.ParsingXmlUsingXpath.ResponseTrainee.
setMessage(java.lang.reflect.Array)
at java.lang.Class.getMethod(Class.java:1607)
at pk.training.basitMahmood.ParsingXmlUsingXpath.TryXpath.
invokeMethodDynamically(TryXpath.java:498)
...

我做错了什么?

谢谢

最佳答案

在出现错误的行中试试这个:

myMethod = myClass.getMethod(methodName, new Class[] { String[].class });

关于java - 如何使用反射设置数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17651994/

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