How to invoke a method in java using reflection

前端 未结 4 1531
盖世英雄少女心
盖世英雄少女心 2020-12-03 12:30

How can I invoke a method with parameters using reflection ?

I want to specify the values of those parameters.

4条回答
  •  不思量自难忘°
    2020-12-03 12:56

    this is the easiest way I know of, it needs to be surrounded with try & catch:

    Method m = .class.getDeclaredMethod("", arg_1.class, arg_2.class, ... arg_n.class); result = () m.invoke(null,(Object) arg_1, (Object) arg_2 ... (Object) arg_n);

    this is for invoking a static method, if you want to invoke a non static method, you need to replace the first argument of m.invoke() from null to the object the underlying method is invoked from.

    don't forget to add an import to java.lang.reflect.*;

提交回复
热议问题