面试题答案
一键面试- 获取私有方法:
- 使用
Class.getDeclaredMethod
方法,该方法可以获取类的所有声明的方法,包括私有方法。
- 使用
- 调用私有方法:
- 通过反射获取到的
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);
}
}