Zweistein2 Zweistein2 - 1 month ago 8
Java Question

java reflections list NoSuchMethodException

I'm currently working on a commandline-client for automated testing. For this, I want to be able to perform a request just by a given name, so I have to use reflection.

However, I get the following error:


NoSuchMethodException: java.util.ArrayList.add(some.path.Foo)


on this code:

Object job = Class.forName(sClassName).getConstructor().newInstance();

List<?> jobObject = (List<?>) Request.getClass().getDeclaredMethod(sMethodName).invoke(Request);
jobObject.getClass().getDeclaredMethod("add", job.getClass()).invoke(Request, job);


On the other hand, the following code works (but is not the solution as Foo should be dynamic, not hardcoded)

Object job = Class.forName(sClassName).getConstructor().newInstance();

List<Foo> jobObject = (List<Foo>) Request.getClass().getDeclaredMethod(sMethodName)).invoke(Request);
jobObject.add((Foo)job);


Sidenote:


  • sClassName = some.path.Foo

  • .getDeclaredMethod(sMethod).invoke(Request) returns an Object (which is a List< Foo>)



What I want to achieve is to get the code working with dynamic inputs (for example Bar instead of Foo)

Answer

Due to type erasure, the method add of a List expects at runtime an object of type Object (in other words its signature is boolean add(Object o)) moreover you need to invoke it on jobObject not on Request as it is not a List, so your code should rather be:

 jobObject.getClass().getDeclaredMethod("add", Object.class).invoke(jobObject, job);

Unless I miss something for me you don't even need reflection in this case

List<Object> jobObject = (List<Object>)...
jobObject.add(job);