Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Array using reflection

I have a class in which there is setter and getter like this

private String[] message;

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

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

Now i am trying to call setter using reflection like

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().

But when i come to line

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

i get the following error

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)
...

What i am doing wrong ?

Thanks

like image 931
Basit Avatar asked Mar 20 '26 01:03

Basit


1 Answers

Try this in the line you're getting the error:

myMethod = myClass.getMethod(methodName, new Class[] { String[].class });
like image 161
morgano Avatar answered Mar 22 '26 14:03

morgano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!