lundi 7 novembre 2016

java reflections list NoSuchMethodException

Heyho,

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 reflections. As of this I got the following error:

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

on this code:

Object job = Class.forName("some.path" + mappingTable.getProperty(Kurz + "RequiredJobName")).getConstructor().newInstance();

List<?> jobObject = (List<?>) Request.getClass().getDeclaredMethod(mappingTable.getProperty(Kurz + "RequiredJobMethod")).invoke(Request);
jobObject.getClass().getDeclaredMethod("add", job.getClass()).invoke(Request, job);

while this works completely fine. (But is not the solution as Foo should be dynamic, not hardcoded)

Object job = Class.forName("some.path" + mappingTable.getProperty(Kurz + "RequiredJobName")).getConstructor().newInstance();

List<Foo> jobObject = (List<Foo>) Request.getClass().getDeclaredMethod(mappingTable.getProperty(Kurz + "RequiredJobMethod")).invoke(Request);
jobObject.add((Foo)job);

Sidenote,

  • mappingTable.getProperty(Kurz + "RequiredJobName") returns Foo
  • .getDeclaredMethod(mappingTable.getProperty(Kurz + "RequiredJobMethod")).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)





Aucun commentaire:

Enregistrer un commentaire