MST
星途 面试题库

面试题:Java反射机制在JUnit测试中如何用于获取类的私有方法并调用

假设你有一个包含私有方法的Java类,在JUnit测试环境下,描述如何使用Java反射机制获取并调用该私有方法。请给出关键代码片段示例。
20.1万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
  1. 获取私有方法
    • 使用Class.getDeclaredMethod方法,该方法可以获取类的所有声明的方法,包括私有方法。
  2. 调用私有方法
    • 通过反射获取到的Method对象,需要设置其可访问性,因为私有方法默认是不可访问的,使用method.setAccessible(true)
    • 然后使用method.invoke方法来调用该私有方法。

以下是关键代码片段示例:

import org.junit.jupiter.api.Test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

class TargetClass {
    private String privateMethod(String param) {
        return "Result from private method with param: " + param;
    }
}

public class PrivateMethodTest {
    @Test
    public void testPrivateMethod() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        TargetClass target = new TargetClass();
        // 获取私有方法
        Method privateMethod = TargetClass.class.getDeclaredMethod("privateMethod", String.class);
        // 设置可访问性
        privateMethod.setAccessible(true);
        // 调用私有方法
        String result = (String) privateMethod.invoke(target, "testParam");
        System.out.println(result);
    }
}