4

This is my code to invoke a method dynamically:

String[] parameters = new String[requiredParameters.length];
//here i put some values in the parameters array
method = TestRecommendations.class.getMethod("level1ClassSimilarityForUser",
                                    String[].class);
System.out.println(":" + parameters[0] + ":");
results = (ResultSet) method.invoke(new TestRecommendations(), parameters)

parameters is a string array, and this is the declaration of my level1ClassSimilarityForUser method

public ResultSet level1ClassSimilarityForUser(String[] userURI) {

I am getting this error:

java.lang.IllegalArgumentException: argument type mismatch

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)

1 Answer 1

8

invoke expects an Object[] as second argument (varargs is just a convenience syntax). I think in your case the String[] is not taken as the first vararg argument, but the complete vararg Object[] and thus your single strings are used as arguments which does not match String[].
In your case, explicitly wrapping your parameters in an Object array before giving it to invoke should work.
So do results = (ResultSet) method.invoke(new TestRecommendations(), new Ojbect[] { parameters }) instead

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.