Java通过反射实现方法调用

  • 代码实现

package me.andy.practice.reflect;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

import static junit.framework.Assert.assertEquals;

public class MethodInvokeTest {

    @Test
    public void test_add() throws Exception {
        Class<?> personClass = Calculate.class;
        Object person = personClass.newInstance();
        Method method = personClass.getDeclaredMethod("add", new Class[]{int.class, int.class});
        Object result = method.invoke(person, new Object[]{1, 2});
        assertEquals(result, 3);


    }

    @Test
    public void test_subtract() throws Exception {
        Class<?> personClass = Calculate.class;
        Object person = personClass.newInstance();
        Method method = personClass.getDeclaredMethod("subtract", new Class[]{int.class, int.class});
        method.setAccessible(true);
        Object result = method.invoke(person, new Object[]{2, 1});
        assertEquals(result, 1);
    }


}

class Calculate {

     public int add(int a, int b) {
        return a + b;
    }

    private int subtract(int a, int b) {
        return a - b;
    }

}


  • 代码讲解

创建对象:Object person = personClass.newInstance();

获取方法: Method method = personClass.getMethod("add", new Class[]{int.class, int.class});

方法调用:Object result = method.invoke(person, new Object[]{1, 2});

访问私有方法:method.setAccessible(true);


你可能感兴趣的:(Java通过反射实现方法调用)