面试题答案
一键面试- 获取类对象:首先需要获取包含私有方法的类的
Class
对象。假设类名为TargetClass
,可以通过Class.forName("全限定类名")
或者TargetClass.class
获取。 - 获取私有方法:使用
getDeclaredMethod
方法获取私有方法,该方法接收方法名和参数类型作为参数。因为是私有方法,所以需要通过setAccessible(true)
来设置访问权限。 - 调用私有方法:通过获取到的
Method
对象,调用invoke
方法来调用私有方法,invoke
方法接收对象实例和方法参数。
关键代码片段如下:
import java.lang.reflect.Method;
public class ReflectionExample {
public static void main(String[] args) throws Exception {
// 获取类对象
Class<?> targetClass = Class.forName("TargetClass");
// 获取私有方法
Method privateMethod = targetClass.getDeclaredMethod("privateMethod", 参数类型列表);
privateMethod.setAccessible(true);
// 创建类的实例(假设存在无参构造函数)
Object targetObject = targetClass.newInstance();
// 调用私有方法
privateMethod.invoke(targetObject, 方法参数列表);
}
}
class TargetClass {
private void privateMethod(参数列表) {
// 方法实现
System.out.println("私有方法被调用");
}
}
将上述代码中的TargetClass
替换为实际的类名,privateMethod
替换为实际的私有方法名,参数类型列表
和方法参数列表
替换为实际的参数类型和参数值。