Java reflection, where the method parameter is an interface

First of all, let me say that I support someone’s poorly designed code, so I am limited in how much I can change it.

Now what happens is that they created a series of methods that are called by reflection. One of these methods takes the map as one of its arguments. At run time, this map is implemented using a Hashtable.

Here's the problem - I get a NoSuchMethodException because it is looking for a method with a Hashtable as an argument, even if the Hashtable implements the Map interface. What confuses me is that if I don’t use reflection (the main design change in this case) and pass the Hashtable, it will refer to the method with the Map parameter - so why doesn’t it work the same when I use reflection

Given that I pretty much have to adhere to reflection, is there a way to get a method with a Map argument to call when I pass it a class that implements this interface?

If you want, I can make fun of the code to demonstrate ...

+3
source share
2 answers

If you use getMethod(String name, Class[] parameterTypes)from java.lang.Class, you need to specify the parameter types expressed in the signature of the interface method (static type), and not the type of the object at run time (dynamic type).

So, for methodXyz(Map map)instead:

Method m = cl.getMethod("methodXyz", new Class[]{argument.getClass()});

do the following:

Method m = cl.getMethod("methodXyz", new Class[]{Map.class});
+4
source

I had a similar problem. I see 2 solutions:

Solution 1: You can develop a more sophisticated search method.

, :

. (), - ( ), , ( ). , .

. , /. ...

solution 2: , , . , .

, "invokeMethod (String methodName, Object [] paramters)" "invokeMethod (String methodName, Class [] methodParamTypes, Object [] parameters)".

+1

Source: https://habr.com/ru/post/1761350/


All Articles