java反射在单元测试中的应用

java反射

反射的意义

  • 单元测试private方法

代码

实体类

package com.xin.test;

/**
 * Created by r.x on 2017/7/6.
 */
public class User {
    private String name;
    private int age;

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

待反射的类

package com.xin.test;

/**
 * Created by r.x on 2017/7/6.
 */
public class ReflectDemo {
    public void outer(User user, String job, int time) {
        System.out.println("公众信息:" + user.getName() + "," + user.getAge() + "岁。表面从事" + job + "工作长达" + time + "年");
    }

    public void inner(User user, String job, int time) {
        System.out.println("内部消息:" + user.getName() + "," + user.getAge() + "岁。实际从事" + job + "工作长达" + time + "年");
    }
}

单元测试类

package com.xin.test;

import org.junit.Test;
import java.lang.reflect.Method;

/**
 * Created by r.x on 2017/7/6.
 */
public class ReflectDemoTest {
    @Test
    public void testOuter() throws Exception{
        Class<?> clazz = ReflectDemo.class;
        Object reflectDemo = clazz.newInstance();
        // 通过getMethod获取public方法
        // **注意:int.class不能写成Integer.class,否则会报NoSuchMethodException**
        Method outer = clazz.getMethod("outer", User.class, String.class, int.class);
        User user = new User() {
            {
                setName("老王");
                setAge(38);
            }
        };
        outer.invoke(reflectDemo, user, "程序猿", 5);
    }

    @Test
    public void testInner() throws Exception {
        Class<?> clazz = Class.forName("com.xin.test.ReflectDemo");
        Object reflectDemo = clazz.newInstance();
        // 通过getDeclaredMethod获取
        Method inner = clazz.getDeclaredMethod("inner", User.class, String.class, int.class);
        // 必须设置为true,否则会抛出NoSuchMethodException
        inner.setAccessible(true);
        User user = new User() {
            {
                setName("老王");
                setAge(38);
            }
        };
        inner.invoke(reflectDemo, user, "单身狗", 25);
    }
}

运行结果

内部消息:老王,38岁。实际从事单身狗工作长达25年
公众信息:老王,38岁。表面从事程序猿工作长达5年
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章