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

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

    First, don't. Avoid this sort of code. It tends to be really bad code and insecure too (see section 6 of Secure Coding Guidelines for the Java Programming Language, version 2.0).

    If you must do it, prefer java.beans to reflection. Beans wraps reflection allowing relatively safe and conventional access.

提交回复
热议问题