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

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

    I do this like this:

    try {
        YourClass yourClass = new YourClass();
        Method method = YourClass.class.getMethod("yourMethodName", ParameterOfThisMethod.class);
        method.invoke(yourClass, parameter);
    } catch (Exception e) {
        e.printStackTrace();
    }
    

提交回复
热议问题