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

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

    Coding from the hip, it would be something like:

    java.lang.reflect.Method method;
    try {
      method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);
    } catch (SecurityException e) { ... }
      catch (NoSuchMethodException e) { ... }
    

    The parameters identify the very specific method you need (if there are several overloaded available, if the method has no arguments, only give methodName).

    Then you invoke that method by calling

    try {
      method.invoke(obj, arg1, arg2,...);
    } catch (IllegalArgumentException e) { ... }
      catch (IllegalAccessException e) { ... }
      catch (InvocationTargetException e) { ... }
    

    Again, leave out the arguments in .invoke, if you don't have any. But yeah. Read about Java Reflection

提交回复
热议问题