【Java基础】Java反射——Private Fields and Methods
Despite the common belief it is actually possible to access private fields and methods of other classes via Java Reflection. It is not even that difficult. This can be very handy during unit testing. This text will show you how.
Note: This only works when running the code as a standalone Java application, like you do with unit tests and regular applications. If you try to do this inside a Java Applet, you will need to fiddle around with the SecurityManager. But, since that is not something you need to do very often, it is left out of this text so far.
Note: There has been a lot of talk about disabling the ability to access private fields via reflection from Java 9. From my experiments it seems to still be possible in Java 9, but be aware that this might change in a future Java version.
Accessing Private Fields
To access a private field you will need to call the Class.getDeclaredField(String name)
or Class.getDeclaredFields()
method. The methods Class.getField(String name)
and Class.getFields()
methods only return public fields, so they won't work. Here is a simple example of a class with a private field, and below that the code to access that field via Java Reflection:
public class PrivateObject {
private String privateString = null;
public PrivateObject(String privateString) {
this.privateString = privateString;
}
}
PrivateObject privateObject = new PrivateObject("The Private Value");
Field privateStringField = PrivateObject.class.
getDeclaredField("privateString");
privateStringField.setAccessible(true);
String fieldValue = (String) privateStringField.get(privateObject);
System.out.println("fieldValue = " + fieldValue);
This code example will print out the text "fieldValue = The Private Value", which is the value of the private field privateString
of the PrivateObject
instance created at the beginning of the code sample.
Notice the use of the method PrivateObject.class.getDeclaredField("privateString")
. It is this method call that returns the private field. This method only returns fields declared in that particular class, not fields declared in any superclasses.
Notice the line in bold too. By calling Field.setAcessible(true)
you turn off the access checks for this particular Field
instance, for reflection only. Now you can access it even if it is private, protected or package scope, even if the caller is not part of those scopes. You still can't access the field using normal code. The compiler won't allow it.
Accessing Private Methods
To access a private method you will need to call the Class.getDeclaredMethod(String name, Class[] parameterTypes)
or Class.getDeclaredMethods()
method. The methods Class.getMethod(String name, Class[] parameterTypes)
and Class.getMethods()
methods only return public methods, so they won't work. Here is a simple example of a class with a private method, and below that the code to access that method via Java Reflection:
public class PrivateObject {
private String privateString = null;
public PrivateObject(String privateString) {
this.privateString = privateString;
}
private String getPrivateString(){
return this.privateString;
}
}
PrivateObject privateObject = new PrivateObject("The Private Value");
Method privateStringMethod = PrivateObject.class.
getDeclaredMethod("getPrivateString", null);
privateStringMethod.setAccessible(true);
String returnValue = (String)
privateStringMethod.invoke(privateObject, null);
System.out.println("returnValue = " + returnValue);
This code example will print out the text "returnValue = The Private Value", which is the value returned by the method getPrivateString()
when invoked on the PrivateObject
instance created at the beginning of the code sample.
Notice the use of the method PrivateObject.class.getDeclaredMethod("privateString")
. It is this method call that returns the private method. This method only returns methods declared in that particular class, not methods declared in any superclasses.
Notice the line in bold too. By calling Method.setAcessible(true)
you turn off the access checks for this particular Method
instance, for reflection only. Now you can access it even if it is private, protected or package scope, even if the caller is not part of those scopes. You still can't access the method using normal code. The compiler won't allow it.
【Java基础】Java反射——Private Fields and Methods的更多相关文章
- 黑马程序员:Java基础总结----反射
黑马程序员:Java基础总结 反射 ASP.Net+Android+IO开发 . .Net培训 .期待与您交流! 反射 反射的基石:Class类 Class类代表Java类,它的各个实例对象又分别 ...
- java基础---->java中正则表达式二
跟正则表达式相关的类有:Pattern.Matcher和String.今天我们就开始Java中正则表达式的学习. Pattern和Matcher的理解 一.正则表达式的使用方法 一般推荐使用的方式如下 ...
- Java基础-Java中23种设计模式之常用的设计模式
Java基础-Java中23种设计模式之常用的设计模式 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.设计模式分类 设计模式是针对特定场景给出的专家级的解决方案.总的来说设 ...
- Java基础-JAVA中常见的数据结构介绍
Java基础-JAVA中常见的数据结构介绍 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.什么是数据结构 答:数据结构是指数据存储的组织方式.大致上分为线性表.栈(Stack) ...
- Java基础-Java中的堆内存和离堆内存机制
Java基础-Java中的堆内存和离堆内存机制 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任.
- Java基础-Java中的内存分配与回收机制
Java基础-Java中的内存分配与回收机制 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一. 二.
- Java基础-Java中的并法库之重入读写锁(ReentrantReadWriteLock)
Java基础-Java中的并法库之重入读写锁(ReentrantReadWriteLock) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 在学习Java的之前,你可能已经听说过读 ...
- Java基础-Java中的并法库之线程池技术
Java基础-Java中的并法库之线程池技术 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.什么是线程池技术 二.
- Java基础-Java数据类型
Java基础-Java数据类型 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.数据类型的作用 数据类型就是一组值,以及这一组值上的操作,数据类型可以决定数据的存储方式,取值范围 ...
随机推荐
- 一次Java线程池误用(newFixedThreadPool)引发的线上血案和总结
一次Java线程池误用(newFixedThreadPool)引发的线上血案和总结 这是一个十分严重的线上问题 自从最近的某年某月某天起,线上服务开始变得不那么稳定(软病).在高峰期,时常有几台机器的 ...
- c++学习笔记2(const关键词的用法)
定义常量指针 优势(便于类型检查,define无类型检查(目前不是很理解)) (函数参数为常量指针时,可避免函数内部不小心改变参数指针所指的地方,如有出现此类语句,编译则会报错) strcpy:复制字 ...
- python-文件操作(一)
目录 文件操作 1.什么是文件? 2.操作文件的方法: 3.路径分类: 4.如何取消特殊字符的功能: 5.对文件的操作有:读.写.追加内容 6.with上下文管理 7.文件操作方法详细: 1.r-读操 ...
- 团队内部密码共享方案:KeePassXC+微盘(企业微信)
目录 需求描述 适用场景 安装使用 KeePassXC初始化 浏览器插件安装设置 1.火狐 2.Edge 3.Chrome 软件-插件的链接 登陆网站并保存密码 (企业微信)微盘共享内部数据库 其他 ...
- SQL语句修改字段类型与第一次SQLServer试验解答
SQL语句修改字段类型 mysql中 alert table name modify column name type; 例子:修改user表中的name属性类型为varchar(50) alert ...
- [bzoj1416]神奇的口袋
容易发现操作任意次并不会改变每一个点的概率(因为每一个点加d的概率相同,期望与原数成比例),然后直接输出即可(要用高精度) 1 #include<bits/stdc++.h> 2 usin ...
- [nowcoder5669A]Ancient Distance
对于一个$k$,可以二分枚举答案并判断,判断过程可以贪心找最深的点(线段树区间max)+倍增+线段树区间覆盖(清0)来实现,时间复杂度$o(klog_{2}n)$ 考虑反过来,暴力枚举答案$x$并求出 ...
- PHP绕过MD5比较的各种姿势
1.用==进行弱类型比较时, 可以通过两个0e开头后面纯数字的md5绕过 php在进行弱类型比较时,如果为字符串为纯数字,包括浮点数.科学计数法.十六进制数等,都会转化为数字类型再进行比较,利用这点, ...
- UI自动化测试:App的WebView页面中,当搜索栏无搜索按钮时处理方法
一.遇到的问题 在做移动端的UI自动化测试时,经常会遇到上图所示的搜索框,这里有个麻烦就是搜索框没有"搜索"按钮,UI自动化测试时不能确认搜索. 要解决这个问题,我们可以通过 dr ...
- 统计学习2:线性可分支持向量机(Scipy实现)
1. 模型 1.1 超平面 我们称下面形式的集合为超平面 \[\begin{aligned} \{ \bm{x} | \bm{a}^{T} \bm{x} - b = 0 \} \end{aligned ...