Reflection - Getting Different Results From HashMap - LinkedHashMap

I will keep it concise, I have a class Dogas shown below:

public class Dog 
{
   public void Foo() 
   { 
      System.out.println("Right Call");
   }

   public void Boo()
   {
     System.out.println("Wrong Call");
   }
}

and the main method, for example:

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 randomly provides outputs Right Callor Wrong Call.

I need to be sure that every time I put the key "foo", it should call the method Foo()instead Boo().

Apparently, this does not alleviate my problem with the method call. How can I solve this problem? I have to call the right method every time. I am completely new to this thinking, is there something that I should not do, or something that I am doing wrong? Or is there a better way to implement this method?

EDIT: LinkedHashMap, .

.

+4
5

javadoc Class.getMethods():

.

, , 0 Foo(). . , Foo.

, Reflection, , , . , , , - . .

+8

, - - :

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();
}

, getMethods() , . Foo ( Foo Java), , Class.getMethod("foo") .

+5

getMethods() , , method[0] - Foo() ( Boo()). , "foo".

+3

:

Dog d = new Dog();
map.put("foo", d.getClass().getMethod("Foo");
Method m = map.get("foo");
m.invoke()

, , catch , . getMethods(). , , , getMethod, . , .

+1

, .

    Dog d = new Dog();
    try {
        d.getClass.getMethod("Foo").invoke(d, null);
    } catch (IllegalAccessException | IllegalArgumentException
            | InvocationTargetException | NoSuchMethodException e) {
        e.printStackTrace();
    }

, , NoSuchMethodException.

, api, , . .

+1

All Articles