How do I invoke a Java method when given the method name as a string?

前端 未结 21 2107
耶瑟儿~
耶瑟儿~ 2020-11-21 04:50

If I have two variables:

Object obj;
String methodName = \"getName\";

Without knowing the class of obj, how can I call the met

21条回答
  •  长情又很酷
    2020-11-21 05:26

    for me a pretty simple and fool proof way would be to simply make a method caller method like so:

    public static object methodCaller(String methodName)
    {
        if(methodName.equals("getName"))
            return className.getName();
    }
    

    then when you need to call the method simply put something like this

    //calling a toString method is unnessary here, but i use it to have my programs to both rigid and self-explanitory 
    System.out.println(methodCaller(methodName).toString()); 
    

提交回复
热议问题