`
yangzb
  • 浏览: 3502871 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Java Reflection: Private Fields and Methods

    博客分类:
  • Java
阅读更多

from:http://tutorials.jenkov.com/java-reflection/index.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.

Here is a list of the topics covered in this text:

  1. Accessing Private Fields
  2. Accessing Private Methods

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.

分享到:
评论

相关推荐

    Effective Java 3rd edition(Effective Java第三版英文原版)附第二版

    Item 16: In public classes, use accessor methods, not public fields Item 17: Minimize mutability Item 18: Favor composition over inheritance Item 19: Design and document for inheritance or else ...

    java反射操作父类所有属性和方法

    在Java编程语言中,反射(Reflection)是一项强大的特性,它允许程序在运行时动态地获取类的信息,并能够直接操作这些信息。通过反射,我们可以获取类的字段、方法等元数据,甚至可以创建实例并调用其方法。本文将...

    Java零基础 - Java的加载与执行原理剖析.md

    System.out.println("Methods:"); for (Method method : methods) { System.out.println(method.getName()); } } } class MyClass { private int myNumber; public void setMyNumber(int number) { my...

    java反射机制

    ### Java反射机制详解 #### 引言 Java反射机制,作为Java语言动态特性的核心,赋予了Java在运行时分析和操作类的能力。这不仅增强了Java的灵活性,还使其成为处理元数据、进行代码生成、执行框架开发以及实现依赖...

    java中dao层反射使用.doc

    Java 中 DAO 层反射使用 Java 中的 DAO 层是数据访问对象的缩写,主要负责数据的访问和操作。在 Java 中,反射机制是实现 DAO 层的关键技术之一。本文将对 Java 中 DAO 层反射使用进行详细的介绍。 反射机制 Java...

    Java语言规范 SE 8 版本-官方英文版-带书签文字版.pdf

    类是创建对象的蓝图,包含属性(Fields)和方法(Methods)。 - 包(Package):组织类的容器,提供命名空间管理,避免类名冲突。 - 接口(Interface):定义了一组抽象方法,是多继承的实现方式,用于定义行为...

    初学者必看的JAVA基础教程

    5. **类的成员**:包括属性(fields)和方法(methods),了解如何声明、初始化和访问它们。 6. **访问修饰符**:如public、private、protected和默认(package-private),理解它们对类和成员的可见性影响。 7. *...

    Java类的反射与动态加载

    在Java中,每一个类都被编译成.class文件,这些文件包含了类的所有信息,包括字段(fields)、方法(methods)和构造器(constructors)。反射API提供了一组类和接口,如Class、Constructor、Method和Field,它们...

    java学习大总结.pdf

    类的成员包括属性(Fields)和方法(Methods),属性用于存储数据,方法用于执行操作。属性可以有默认的初始化值,也可以通过构造器来设置。方法则包含了一段可执行的代码,可以操作和修改类的属性。此外,类的成员...

    Professional C# 3rd Edition

    Sealed Classes and Methods 115 Constructors of Derived Classes 116 Modifiers 122 Visibility Modifiers 122 Other Modifiers 123 Interfaces 123 Defining and Implementing Interfaces 125 Derived Interfaces...

    CorsoPOO:面向对象编程(Java)课程资料库

    类是对象的模板,它描述了对象的属性(fields)和行为(methods)。理解如何定义类、创建对象以及如何通过对象进行交互是学习OOP的基础。 2. **封装**:封装是将数据和操作这些数据的方法绑定在一起的过程,以防止...

    C#语言参考

    - **元数据和反射**(Metadata and Reflection):允许程序在运行时检查自身和其它程序集的信息。 - **多线程**(Multithreading):C#提供对多线程的支持,允许同时执行多个任务。 - **.NET Framework和.NET ...

    如何查找程序集特殊成员例子C#.net源代码编写

    4. 查找特殊成员:对于每个类型,可以使用Type对象的方法来查找特殊成员,如GetFields、GetMethods、GetProperties等,这些方法接受BindingFlags参数来指定搜索范围,如IsPrivate、IsProtected、IsInternal等。...

    dll及exe中的字段属性及方法浏览

    它们可以是私有的(private),仅在类内部访问,也可以是公共的(public),允许外部代码直接访问。此外,还有受保护的(protected)字段,仅允许子类访问,以及内部的(internal)字段,限于同一命名空间内的代码...

Global site tag (gtag.js) - Google Analytics