0

I am looking at this question

How do I invoke a Java method when given the method name as a string?

and applying what the fist answer says

This is my code to call a method dyanmically, and its argument is an array of string

java.lang.reflect.Method method;
                    try {
                        String [] requiredParameters = testService.getRequiredParameters();
                        String [] parameters = new String[requiredParameters.length];
                        for (int i = 0; i<requiredParameters.length ; i++){
                            String valueRequiredParameter = request.getParameter(requiredParameters[i]);
                            parameters[i] = valueRequiredParameter;
                        }
                          method = new TestRecommendations().getClass().getMethod(service, parameters);
                        } catch (SecurityException e) {
                          // exception handling omitted for brevity
                        } catch (NoSuchMethodException e) {
                          // exception handling omitted for brevity
                        }

i get compiler error on the getMethod states :

The method getMethod(String, Class<?>...) in the type Class<capture#1-of ? extends TestRecommendations> is not applicable for the arguments (String, String[])

And this is the type of method i want to call dynamcially

public ResultSet level0ForUser(String ... userURI) {
Community
  • 1
  • 1
Ania David
  • 1,068
  • 1
  • 11
  • 30

2 Answers2

2

you're passing arguments with the wrong type. Your getMethod call accepts one String instance and multiple Class instances. And you're trying to pass one String and String array

via documentation:

getMethod(String name, Class<?>... parameterTypes)

Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object. The name parameter is a String specifying the simple name of the desired method. The parameterTypes parameter is an array of Class objects that identify the method's formal parameter types, in declared order. If parameterTypes is null, it is treated as if it were an empty array.

so you need to pass Class var arg which consists of all the arguments types of desired method. For your method you should write something like:

Method m = TestRecommendations.class.getMethod("service", String[].class);
Community
  • 1
  • 1
Cootri
  • 3,486
  • 16
  • 27
2

Get the method with something like:

Method m = TestRecommendations.class.getMethod("level0ForUser", String[].class);

And invoke like:

m.invoke(new TestRecommendations(), new Object[] { new String[]{ "A", "B", "C" } } );
Jorn Vernee
  • 26,917
  • 3
  • 67
  • 80