I'll keep it brief, I have a Dog
class like the following:
public class Dog
{
public void Foo()
{
System.out.println("Right Call");
}
public void Boo()
{
System.out.println("Wrong Call");
}
}
and a main method like following:
HashMap<String, Method> map = new HashMap<String, Method>();
Dog d = new Dog();
Method[] method = d.getClass().getMethods();
map.put("foo", method[0]);
Method a = map.get("foo");
try {
a.invoke(d, null);
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
e.printStackTrace();
}
Whenever I run it again, it just arbitrarily gives Right Call
or Wrong Call
outputs.
I need to be sure that every time I place the "foo"
key, It must to be calling the Foo()
method, instead of Boo()
.
Apparently, It doesn't ease my "method call" problem. How can I overcome this issue? I must be calling the right method every time. I'm quite new to this reflections stuff, is there anything that I shouldn't be doing, or something that I'm doing wrong? Or is there a better way to implement this method calling?
EDIT: I've also tried LinkedHashMap
, however, the result is the same.
Thank you.
This has nothing to do with putting the method in a map, as far as I can tell - you can remove the map part entirely and still face the same issue:
Dog d = new Dog();
Method methods = d.getClass().getMethods();
Method a = methods[0];
try {
a.invoke(d, null);
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
e.printStackTrace();
}
Fundamentally, you're seeing the fact that getMethods()
doesn't return the methods from a class in an order you should rely on. If you want to specifically call your Foo
method (which should be foo
to follow Java naming conventions), you should probably be using Class.getMethod("foo")
to get the method by name.
See more on this question at Stackoverflow