How to invoke a method in java using reflection

前端 未结 4 1533
盖世英雄少女心
盖世英雄少女心 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条回答
  •  Happy的楠姐
    2020-12-03 12:57

    Here's a simple example of invoking a method using reflection involving primitives.

    import java.lang.reflect.*;
    
    public class ReflectionExample {
        public int test(int i) {
            return i + 1;
        }
        public static void main(String args[]) throws Exception {
            Method testMethod = ReflectionExample.class.getMethod("test", int.class);
            int result = (Integer) testMethod.invoke(new ReflectionExample(), 100);
            System.out.println(result); // 101
        }
    }
    

    To be robust, you should catch and handle all checked reflection-related exceptions NoSuchMethodException, IllegalAccessException, InvocationTargetException.

提交回复
热议问题