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

前端 未结 21 2093
耶瑟儿~
耶瑟儿~ 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:10

    //Step1 - Using string funClass to convert to class
    String funClass = "package.myclass";
    Class c = Class.forName(funClass);
    
    //Step2 - instantiate an object of the class abov
    Object o = c.newInstance();
    //Prepare array of the arguments that your function accepts, lets say only one string here
    Class[] paramTypes = new Class[1];
    paramTypes[0]=String.class;
    String methodName = "mymethod";
    //Instantiate an object of type method that returns you method name
     Method m = c.getDeclaredMethod(methodName, paramTypes);
    //invoke method with actual params
    m.invoke(o, "testparam");
    

提交回复
热议问题