First off let me say I am maintaining someone else’s poorly designed code so I am limited in how much I can change it.
Now what is happening is that they have created a series of methods that are invoked by reflection. One of those methods takes a Map as one of its arguments. At runtime this Map is implemented with a Hashtable.
Here’s the problem – I get a NoSuchMethodException because it is looking for a method with Hashtable as an argument even though a Hashtable implements the Map interface. What is confusing me is that if I don’t use reflection (a major design change in this case) and passed a Hashtable it would invoke the method with the Map parameter – so why doesn’t it work the same way when I use reflection?
Given that I pretty much have to stick with reflection is there any way to get the method with the Map argument to get invoked when I pass it a class that implements that interface?
If you want I can mock some code up to demonstrate…
If you are using
getMethod(String name, Class[] parameterTypes)fromjava.lang.Class, you need to specify parameter types as expressed in the method signature of the interface (static type), not the type of the object at run-time (dynamic type).So, for
methodXyz(Map map), instead of:do this: