Java Reflection - Private Fields and Methods

本文介绍如何使用Java反射API访问其他类中的私有字段和方法,这对于单元测试非常有用。文中提供了示例代码展示如何获取并操作这些通常不可见的成员。

http://tutorials.jenkov.com/java-reflection/private-fields-and-methods.html


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.

Accessing Private Fields

To access a private field you will need to call the Class.getDeclaredField(String name) orClass.getDeclaredFields() method. The methods Class.getField(String name) andClass.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 fieldprivateString 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.



【最优潮流】直流最优潮流(OPF)课设(Matlab代码实现)内容概要:本文档主要围绕“直流最优潮流(OPF)课设”的Matlab代码实现展开,属于电力系统优化领域的教学与科研实践内容。文档介绍了通过Matlab进行电力系统最优潮流计算的基本原理与编程实现方法,重点聚焦于直流最优潮流模型的构建与求解过程,适用于课程设计或科研入门实践。文中提及使用YALMIP等优化工具包进行建模,并提供了相关资源下载链接,便于读者复现与学习。此外,文档还列举了大量与电力系统、智能优化算法、机器学习、路径规划等相关的Matlab仿真案例,体现出其服务于科研仿真辅导的综合性平台性质。; 适合人群:电气工程、自动化、电力系统及相关专业的本科生、研究生,以及从事电力系统优化、智能算法应用研究的科研人员。; 使用场景及目标:①掌握直流最优潮流的基本原理与Matlab实现方法;②完成课程设计或科研项目中的电力系统优化任务;③借助提供的丰富案例资源,拓展在智能优化、状态估计、微电网调度等方向的研究思路与技术手段。; 阅读建议:建议读者结合文档中提供的网盘资源,下载完整代码与工具包,边学习理论边动手实践。重点关注YALMIP工具的使用方法,并通过复现文中提到的多个案例,加深对电力系统优化问题建模与求解的理解。
### Java 反射高级特性详解 #### 获取类的信息 Java反射机制允许程序在运行期间动态获取类的相关信息。通过`Class`类可以访问到类的结构,包括字段、方法以及构造器等[^1]。 ```java import java.lang.reflect.Field; import java.lang.reflect.Method; public class ReflectionInfo { public static void main(String[] args) throws Exception { Class<?> clazz = Class.forName("java.util.ArrayList"); // 输出所有公共字段名称及其修饰符 Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { System.out.println(field); } // 输出所有声明的方法签名 Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { System.out.println(method.getName() + "()" ); } } } ``` #### 动态创建对象并调用其成员 利用反射不仅可以查询类定义还可以实例化新对象甚至执行特定的操作。下面的例子展示了如何使用构造函数来构建一个新的字符串对象,并打印出来[^3]。 ```java import java.lang.reflect.Constructor; public class DynamicInstanceExample { public static void main(String[] args) { try { Class<?> clazz = Class.forName("java.lang.String"); Constructor<?> constructor = clazz.getConstructor(String.class); // 创建对象实例 Object instance = constructor.newInstance("Hello, Reflection!"); System.out.println("Instance: " + instance); } catch (Exception e) { e.printStackTrace(); } } } ``` #### 修改私有属性值 即使某些变量被标记为private也可以借助于setAccessible(true),从而绕过正常的存取控制检查来进行读写操作。 ```java import java.lang.reflect.Field; public class PrivateAccessTest { private String secretMessage = "This is a hidden message."; public static void main(String[] args) throws Exception{ PrivateAccessTest testObject = new PrivateAccessTest(); Class<?> clazz = testObject.getClass(); Field field = clazz.getDeclaredField("secretMessage"); // 设置可访问标志位为true field.setAccessible(true); // 更改私有字段的内容 field.set(testObject,"New Message!"); // 打印修改后的结果 System.out.println((String)field.get(testObject)); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值