Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection - Getting different results from HashMap - LinkedHashMap

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.

like image 583
Burak. Avatar asked Dec 01 '22 14:12

Burak.


1 Answers

From the javadoc of Class.getMethods():

The elements in the array returned are not sorted and are not in any particular order.

Yet, your code assumes that the element at index 0 is the method Foo(). Don't make this assumption. Find the method which has the name Foo.

That said, Reflection is probably not the right tool for the job you're trying to do. You should explain, at a higher level, what you're trying to do and why you think using reflection is a good idea. Usually, it's not.

like image 187
JB Nizet Avatar answered Dec 10 '22 14:12

JB Nizet