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:

  1. public class PrivateObject {
  2. private String privateString = null;
  3. public PrivateObject(String privateString) {
  4. this.privateString = privateString;
  5. }
  6. }
  7. PrivateObject privateObject = new PrivateObject("The Private Value");
  8. Field privateStringField = PrivateObject.class.
  9. getDeclaredField("privateString");
  10. privateStringField.setAccessible(true);
  11. String fieldValue = (String) privateStringField.get(privateObject);
  12. 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:

  1. public class PrivateObject {
  2. private String privateString = null;
  3. public PrivateObject(String privateString) {
  4. this.privateString = privateString;
  5. }
  6. private String getPrivateString(){
  7. return this.privateString;
  8. }
  9. }
  10. PrivateObject privateObject = new PrivateObject("The Private Value");
  11. Method privateStringMethod = PrivateObject.class.
  12. getDeclaredMethod("getPrivateString", null);
  13. privateStringMethod.setAccessible(true);
  14. String returnValue = (String)
  15. privateStringMethod.invoke(privateObject, null);
  16. 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的更多相关文章

  1. 黑马程序员:Java基础总结----反射

    黑马程序员:Java基础总结 反射   ASP.Net+Android+IO开发 . .Net培训 .期待与您交流! 反射 反射的基石:Class类 Class类代表Java类,它的各个实例对象又分别 ...

  2. java基础---->java中正则表达式二

    跟正则表达式相关的类有:Pattern.Matcher和String.今天我们就开始Java中正则表达式的学习. Pattern和Matcher的理解 一.正则表达式的使用方法 一般推荐使用的方式如下 ...

  3. Java基础-Java中23种设计模式之常用的设计模式

    Java基础-Java中23种设计模式之常用的设计模式 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任.   一.设计模式分类 设计模式是针对特定场景给出的专家级的解决方案.总的来说设 ...

  4. Java基础-JAVA中常见的数据结构介绍

    Java基础-JAVA中常见的数据结构介绍 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.什么是数据结构 答:数据结构是指数据存储的组织方式.大致上分为线性表.栈(Stack) ...

  5. Java基础-Java中的堆内存和离堆内存机制

    Java基础-Java中的堆内存和离堆内存机制 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任.

  6. Java基础-Java中的内存分配与回收机制

    Java基础-Java中的内存分配与回收机制 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一. 二.

  7. Java基础-Java中的并法库之重入读写锁(ReentrantReadWriteLock)

    Java基础-Java中的并法库之重入读写锁(ReentrantReadWriteLock) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 在学习Java的之前,你可能已经听说过读 ...

  8. Java基础-Java中的并法库之线程池技术

    Java基础-Java中的并法库之线程池技术 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.什么是线程池技术 二.

  9. Java基础-Java数据类型

    Java基础-Java数据类型 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.数据类型的作用 数据类型就是一组值,以及这一组值上的操作,数据类型可以决定数据的存储方式,取值范围 ...

随机推荐

  1. Executors:为什么阿里不待见我?

    大家好,我是Excutors,一个老实的工具类. 有个叫老三的程序员在文章 要是以前有人这么讲线程池,我早就该明白了!里挖了一个坑,说要把我介绍给大家认识认识. 我其实挺委屈的,作为一个没得感情,老实 ...

  2. 【GIS】GeoServer服务Authkey配置记录

    特别感谢:https://www.cnblogs.com/HandyLi/p/8624507.html 1.服务受控配置 2.授权方式 3.Url模式配置 4.Authkey密钥配置 5.使用 在wm ...

  3. cwRsync 实现两台服务器Windows Server 2012 R2间的文件同步(备份)

    sync下载链接:https://pan.baidu.com/s/1aZeGDA5bU9f1h6nxvVJsDw  提取码:jtv3 1.配置IP地址 Server端:192.167.1.2(自定义) ...

  4. 使用Typora+PicGo配置Gitee图床

    1.图床痛点 通常我们用 Typora 写 Markdown 文档,对于文档里面的图片,如果不使用图床,图片都是存放在本地,如果把文档复制到别的地方,还得额外复制图片,特别麻烦. 为了解决这种问题,一 ...

  5. 你真的懂Redis的5种基本数据结构吗?

    摘要: 你真的懂Redis的5种基本数据结构吗?这些知识点或许你还需要看看. 本文分享自华为云社区<你真的懂Redis的5种基本数据结构吗?这些知识点或许你还需要看看>,作者:李子捌. 一 ...

  6. 美团饿了么领取外卖优惠券微信小程序的开发及上线_怎样点外卖省钱_外卖小程序的开发及上线

    都1202年了,估计没人不知道外卖了,那么就有两种人在思考两种问题: 普通人:怎么点外卖划算? 程序员:怎么通过外卖赚钱? 话不多说,为了让你们相信我有能力来讲这块内容,先给你们看一个很简单的小程序: ...

  7. 微信和QQ这么多群,该如何管理好友关系?

    本文节选自<设计模式就该这样学> 1 中介者模式的应用场景 在现实生活中,中介者的存在是不可缺少的,如果没有了中介者,我们就不能与远方的朋友进行交流.各个同事对象将会相互进行引用,如果每个 ...

  8. 第一个vue程序

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  9. HTML四种定位-绝对定位

    绝对定位 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset=&q ...

  10. 数值分析:矩阵奇异值分解(Numpy实现)

    1. 奇异值分解(SVD) (1)奇异值分解 已知矩阵\(\bm{A} \in \R^{m \times n}\), 其奇异值分解为: \[\bm{A} = \bm{U}\bm{S}\bm{V}^T ...