Ahmed Ferjani
Ahmed Ferjani

Reputation: 63

Java method invocation with list

I'm trying to run a function declared in a Java class with arguments (function parameters) extracted from a JSON File.

Java code:

class TestRunner {

    public static void main(String args[]) {
        TestRunner testRunner = new TestRunner();
        try {
            String path = (TestRunner.class.getResource("tests2.json")).getPath();
            ObjectMapper mapper = new ObjectMapper();
            List<Map<String, Object>> myObjects = mapper.readValue(Paths.get(path).toFile(),
                    new TypeReference<List<Map<String, Object>>>() {
                    });
            ArrayList<Integer> list = new ArrayList<>();
            for (Map<String, Object> map : myObjects) {
                ArrayList arr = (ArrayList) map.get("args");
                System.out.println(new TestRunner().executeMethod(testRunner, "fun", arr.toArray()));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public int fun(Integer[] arr) {
        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
            sum = sum + arr[i];
        }
        System.out.println(sum);
        return sum;
    }

    public int fun(Integer a, Integer b, Integer c) {
        return a + b + c;
    }

    public static Object executeMethod(Object objet, String methodName, Object[] parameters) throws Exception {
        Object result;
        Class[] typeParameters = null;
        if (parameters != null) {
            typeParameters = new Class[parameters.length];
            for (int i = 0; i < parameters.length; ++i) {
                typeParameters[i] = parameters[i].getClass();
            }
        }
        Method m = objet.getClass().getMethod(methodName, typeParameters);
        if (Modifier.isStatic(m.getModifiers())) {
            result = m.invoke(null, parameters);
        } else {
            result = m.invoke(objet, parameters);
        }
        return result;
    }
}

JSON File content:

[
  {
    "args": [1, 2, 3],
    "expected": 6
  },
  {
    "args": [[1, 2, 0]],
    "expected": 3
  }
]

It works fine with the first argument, but throws an exception with the second argument which is supposed to be treated as a list of integers in Java, but instead, it's passed to the method invocation with type: java.util.ArrayList

Exception after running code

My question is how I can invoke the method with the correct type of argument which can be []Integer (case for the second args from json) by changing in code only in the executeMethod function.

Upvotes: 1

Views: 489

Answers (1)

Cole Henrich
Cole Henrich

Reputation: 165

You need to learn the basics of programming. When you have a function, in almost any language, the function needs parameters.

For example,

function makeCookies(flour, sugar, water){}

Now if you call makeCookies(brick, broken_glass, battery_acid) of course makeCookies will not work. You have to give it something of type flour, something of type sugar, and something of type water.

I hope you take that example seriously. This is the aspect of programming you do not comprehend. Once you understand the cookies metaphor, you will understand your problem. You tried to pass an ArrayList as parameters, but your function requires an integer because you wrote it that way! It's no big mystery! If you want your function to work, change the parameters that it requires to ArrayList! Or make another function if you need one for Integer[] and one for ArrayList.

Upvotes: 1

Related Questions