是否可以通过反射调用私有属性或方法 [英] Is it possible to invoke private attributes or methods via reflection

查看:674
本文介绍了是否可以通过反射调用私有属性或方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过反射获取静态私有属性的值,但它失败并出现错误。

I was trying to fetch the value of an static private attribute via reflection, but it fails with an error.

Class class = home.Student.class;
Field field = studentClass.getDeclaredField("nstance");
Object obj = field.get(null);

我得到的例外是:

java.lang.IllegalAccessException: Class com.test.ReflectionTest can not access a member of class home.Student with modifiers "private static".

此外,我需要使用以下代码调用私有。

Moreover, there is a private I need to invoke, with the following code.

Method method = studentClass.getMethod("addMarks");
method.invoke(studentClass.newInstance(), 1);

但问题是Student类是单例类,而构造函数是私有的,无法访问。

but the problem is the Student class is a singleton class, and constructor in private, and cannot be accessed.

推荐答案

您可以设置可访问的字段:

You can set the field accessible:

field.setAccessible(true);

这篇关于是否可以通过反射调用私有属性或方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆