Java Reference
In-Depth Information
Bypassing Accessibility Check
You can access even non-accessible fields, methods, and constructors of a class using reflection if the security
manager permits you to do so. You need to get the reference of the desired field, method, and constructor using
the getDeclaredXxx() method of the Class object. Note that using the getXxx() method to get the reference of an
inaccessible field, method, or constructor will throw an exception. The Field , Method, and Constructor classes have
the AccessibleObject class as their ancestor. The AccessibleObject class has a setAccessible(boolean flag)
method. You need to call this method on a field, method, and constructor reference with a true argument to make
that field, method, and constructor accessible to your program.
Listing 3-14 illustrates how to get access to a private field of the Person class, read its value, and set its new value.
You can use the same technique to access inaccessible methods and constructors.
Listing 3-14. Accessing Normally Inaccessible Class Member Using Reflection
// AccessPrivateField.java
package com.jdojo.reflection;
import java.lang.reflect.Field;
public class AccessPrivateField {
public static void main(String[] args) {
Class<Person> personClass= Person.class;
try {
// Create an object of the Person class
Person p = personClass.newInstance();
// Get the reference to name field
Field nameField = personClass.getDeclaredField("name");
// Make the private name field accessible
nameField.setAccessible(true);
// Get the current value of name field
String nameValue = (String) nameField.get(p);
System.out.println("Current name is " + nameValue);
// Set a new value for name
nameField.set(p, "Sherry");
// Read the new value of name
nameValue = (String) nameField.get(p);
System.out.println("New name is " + nameValue);
}
catch(InstantiationException | IllegalAccessException |
NoSuchFieldException | SecurityException |
IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
Current name is Unknown
New name is Sherry
 
Search WWH ::




Custom Search