MST
星途 面试题库

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

在Java反射机制里,假如有一个类含有私有方法,描述如何通过反射获取该私有方法并成功调用它,需要写出关键代码片段。
10.5万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
  1. 获取类对象:首先需要获取包含私有方法的类的Class对象。假设类名为TargetClass,可以通过Class.forName("全限定类名")或者TargetClass.class获取。
  2. 获取私有方法:使用getDeclaredMethod方法获取私有方法,该方法接收方法名和参数类型作为参数。因为是私有方法,所以需要通过setAccessible(true)来设置访问权限。
  3. 调用私有方法:通过获取到的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替换为实际的私有方法名,参数类型列表方法参数列表替换为实际的参数类型和参数值。