Java reflection: accessing private fields and Methods

Source: Internet
Author: User

Origin: 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.

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 callClass.getDeclaredField(String name)OrClass.getDeclaredFields()Method. The methodsClass.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 fieldprivateStringOfPrivateObjectInstance created at the beginning of the code sample.

Notice the use of the methodPrivateObject.class.getDeclaredField("privateString"). It is this method call that returns the private field. This method only returns fields declared in that participant class, not Fields
Declared in any superclasses.

Notice the line in bold too. By callingField.setAcessible(true)You turn off the access checks for this participatesFieldInstance, 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 callClass.getDeclaredMethod(String name, Class[] parameterTypes)OrClass.getDeclaredMethods()Method. The methodsClass.getMethod(String name, Class[]
parameterTypes)
AndClass.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 methodgetPrivateString()When invoked onPrivateObjectInstance created at the beginning
Of the code sample.

Notice the use of the methodPrivateObject.class.getDeclaredMethod("privateString"). It is this method call that returns the private method. This method only returns Methods declared in that participant class, not methods
Declared in any superclasses.

Notice the line in bold too. By callingMethod.setAcessible(true)You turn off the access checks for this participatesMethodInstance, 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.

Author notes:
Sometimes, especially when designing a tool which accepts customizable configurations, we need to create an object whose type is determined at runtime, and invoke some methods of this object. clearly we can not create an object this way: Type OBJ = new type ();
As type is unknown until runtime. Java reflection helps!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.