- Java reflection practice for the record
- Get an Integer class private attribute by reflection
- Exit tips
- Get the String private property by reflection
- Get private attributes of a class by reflection
- Get the constructor of the class by reflection
- Get the Capacity private property of the LinkedBlockingQueue by reflection
- Get the class’s private methods by reflection
- The last
- Java Reflection — Private Fields and Methods
- Accessing Private Fields
- Accessing Private Methods
- How to Access All Private Fields, Methods and Constructors using Java Reflection with Example
- Access Private Fields using Reflection API
- Access Private Methods using Reflection API
- Instantiate a Class by Accessing Private Constructor using Reflection API
Java reflection practice for the record
Class: getDeclaredField reflects all attributes of a Class (including public, private, static, and final). GetDeclaredClasses reflects all inner class objects of the class. GetDeclaredMethod reflects all methods of the class. SetAccessible (true) Disables Java language access checks. If you want to retrieve private members, set this value to true. This is unsafe but improves reflection efficiency.
Get an Integer class private attribute by reflection
- Final properties can be assigned
- Here we take the value property of the Integer class object, assign it a value, and the result of that execution is to fix the value we set for us
public static void main (String[] args) throws Exception < ClassInteger aClass = Integer.class; Field cache = aClass.getDeclaredField("value"); cache.setAccessible(true); Integer a = 10, b = 10; cache.set(a, 16); System.out.println(a); cache.set(b, 12); System.out.println(b); >------------------ Result 16 12Copy the code
Exit tips
static < try < final Class? [] declaredClasses = Integer.class.getDeclaredClasses(); Class? integerClass = declaredClasses[0]; Field cache = integerClass.getDeclaredField("cache"); cache.setAccessible(true); Integer[] integer = (Integer[]) cache.get(integerClass); for (int i = 0; i integer.length; i++) < integer[i] = 3; >> catch (NoSuchFieldException | IllegalAccessException e) < >> public static void main (String[] args) throws Exception/ new Integer() creates a new space in the heap, Println (new Integer(2)); system.out.println (new Integer(2)); System.out.println(Integer.valueOf(2)); Valueof () Integer A = 0; System.out.println(a); Integer c = 127; System.out.println(c); Integer d = 128; System.out.println(d); Integer e = 129; System.out.println(e); > -------------- Result 2 3 3 3 3 128 129Copy the code
Get the String private property by reflection
- In JDK8 a string holds its character contents as an array of char, so some undescribable operation is performed on the value attribute by reflection, which results in the following
public static void main (String[] args) throws Exception < String a = "a"; Class? stringClass = String.class; Field field = stringClass.getDeclaredField("value"); field.setAccessible(true); char[] chars = (char[]) field.get(a); Chars [0] = 'zheng '; System.out.println(a); >-------------- Run the print result zhengCopy the code
Get private attributes of a class by reflection
/** * @Author: ZRH * @Date: 2021/11/19 15:09 */ @Data public class TestModel < private Integer id; private String name; public TestModel () < >public TestModel (String name, Integer id) < this.name = name; this.id = id; >private String sendFun (String name) < return "OK - " + name; >>Copy the code
public static void main (String[] args) throws Exception < TestModel model = new TestModel(); Class? aClass = TestModel.class; Field nameField = aClass.getDeclaredField("name"); nameField.setAccessible(true); nameField.set(model, "zrh"); Field idField = aClass.getDeclaredField("id"); idField.setAccessible(true); idField.set(model, 10000); System.out.println(model.toString()); >-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the execution result TestModel (id = 10000, name = ZRH)Copy the code
Get the constructor of the class by reflection
Public static void main (String[] args) throws Exception/ Obtain the current Class object Class aClass = testModel.class; Constructor = aclass.getconstructor (string.class, integer.class); // Get the Constructor specified for the current class. TestModel model = (TestModel) constructor.newinstance ("222", 3); System.out.println(model); // Get the instance object model = (TestModel) aclass.newinstance () by using the default no-argument constructor of the current class; model.setId(2); model.setName("111"); System.out.println(model); > -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the execution result TestModel (id = 3, name = 222) TestModel (id = 2, name = 111).Copy the code
Get the Capacity private property of the LinkedBlockingQueue by reflection
- A previous article «Dynamic Parameter Configuration for Thread Pool Tuning» described that if you wanted to dynamically configure the queue size of a thread pool, you would need to copy and rewrite it and release the setCapacity operation of its Capacity property.
- The capacity attribute can also be reflected and reassigned, as shown in the following example:
public static void main (String[] args) throws Exception < final LinkedBlockingQueueObject queue = new LinkedBlockingQueue(3); for (int i = 0; i 5; i++) < queue.offer(i); >System.out.println("before size = " + queue.size()); final ClassLinkedBlockingQueue queueClass = LinkedBlockingQueue.class; final Field field = queueClass.getDeclaredField("capacity"); field.setAccessible(true); field.set(queue, 5); for (int i = 0; i 8; i++) < queue.offer(i); >System.out.println("after size copy-code-btn">Copy the code
- The current queue has an initial size of 3, and after reflection and reassignment of capacity to 5, elements are reinserted into the queue until it has a size of 5.
Get the class’s private methods by reflection
Public static void main (String[] args) throws Exception/ Obtain the class instance object final TestModel Model = new TestModel(); Final Class? aClass1 = model.getClass(); / / to get final Method of object of the class Method sendFun = aClass1. GetDeclaredMethod (" sendFun ", String. Class); // Private methods need to disable Java language access check sendFun.setaccessible (true); ZRH = sendfun.invoke (model, "ZRH "); ZRH = sendfun.invoke (model," ZRH "); System.out.println(zrh); > --------------- Result ok-zrhCopy the code
The last
Java Reflection — Private Fields and Methods
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:
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 = The Private Value", which is the value of the private fieldprivateString
of thePrivateObject
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 particularField
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)
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 = 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.
How to Access All Private Fields, Methods and Constructors using Java Reflection with Example
This page will walk through how to access all private fields, methods and constructors using java reflection with example. By default private fields, methods and constructors are not accessible but using java reflection API setAccessible(true) on the instance of Field , Method and Constructor , we can do it. To create the object of a class using private constructor, reflection API provides newInstance() method. Java frameworks like Spring and Struts use reflection API to create custom annotations.
Contents
Access Private Fields using Reflection API
Reflection API can access a private field by calling setAccessible(true) on its Field instance. Find a sample class which has private fields and private methods.
Book.javapackage com.concretepage; public class Book < private String bookName; private int length; private int width; public Book(String bookName, int length, int width) < this.bookName = bookName; this.length = length; this.width = width; >private int pageArea() < return length * width; >private String getBookName() < return bookName; >public void showBookDetail() < System.out.println(pageArea()); System.out.println(getBookName()); >>Now find the Reflection API usage to access private fields. We will show two ways to access private fields.
1. Access all private fields of the class.
2. Access private field by using filed name.Find the example.
PrivateFieldDemo.javapackage com.concretepage; import java.lang.reflect.Field; import java.lang.reflect.Modifier; public class PrivateFieldDemo < //Access all private fields of the class. public void printAllPrivateFields(Book book) throws IllegalArgumentException, IllegalAccessException < Field[] fields = book.getClass().getDeclaredFields(); for (Field field : fields) < if (Modifier.isPrivate(field.getModifiers())) < field.setAccessible(true); System.out.println(field.getName()+" : "+field.get(book)); >> > //Access private field by using filed name. public void printFieldValue(Book book, String fieldName) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException < Field field = book.getClass().getDeclaredField(fieldName); if (Modifier.isPrivate(field.getModifiers())) < field.setAccessible(true); System.out.println(fieldName + " : "+field.get(book)); >> public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException < Book book = new Book("Core Java", 12, 5); PrivateFieldDemo ob = new PrivateFieldDemo(); //print all private fields and their value ob.printAllPrivateFields(book); System.out.println("-----------------------"); //print private field value by field name ob.printFieldValue(book, "bookName"); >>Class.getDeclaredFields(): It returns an array of Field of a class that can be public, protected, private fields but it excludes inherited fields.
Field: It provides information about a class field.
Modifier: It decodes class and member access modifiers using its static methods.
Modifier.isPrivate(): It checks if the filed, method or constructor are private using its modifiers.
field.setAccessible: When we pass true, it allows to access private field.While working with Reflection API, we need to throw or catch some exceptions. These are IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException.
bookName : Core Java length : 12 width : 5 ----------------------- bookName : Core JavaAccess Private Methods using Reflection API
Reflection API can access a private method by calling setAccessible(true) on its Method instance. Here we will show two ways to access private methods using Reflection API.
1. Access all private methods of the class.
2. Access private method by using method name.Find the example.
PrivateMethodDemo.javapackage com.concretepage; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; public class PrivateMethodDemo < //Access all private methods of the class. public void printAllPrivateMethods(Book book) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException < Method[] methods = book.getClass().getDeclaredMethods(); for (Method method : methods) < if (Modifier.isPrivate(method.getModifiers())) < method.setAccessible(true); Object[] args = null; Object ob = method.invoke(book, args); System.out.println(method.getName()+" : "+ ob); >> > //Access private method by using method name. public void printMethodValue(Book book, String methodName) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException < Method method = book.getClass().getDeclaredMethod(methodName); if (Modifier.isPrivate(method.getModifiers())) < method.setAccessible(true); Object[] args = null; Object ob = method.invoke(book, args); System.out.println(methodName + " : "+ ob); >> public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException, SecurityException, NoSuchMethodException < Book book = new Book("Spring Security", 15, 6); PrivateMethodDemo ob = new PrivateMethodDemo(); //print all private methods and their return value ob.printAllPrivateMethods(book); System.out.println("-----------------------"); //print private method return value by method name ob.printMethodValue(book, "getBookName"); >>Class.getDeclaredMethods(): It returns an array of Method of a class that can be public, protected, private methods but it excludes inherited methods.
Method: It provides information about a class method.
method.setAccessible(): When we pass true, it allows to access private method.
method.invoke(): Invokes the calling method. We need to pass class instance and required arguments.getBookName : Spring Security pageArea : 90 ----------------------- getBookName : Spring SecurityInstantiate a Class by Accessing Private Constructor using Reflection API
Reflection API can make accessible its private constructor by calling setAccessible(true) on its Constructor instance and using newInstance() we can instantiate the class. Find the sample class which has two private constructors, one accepts no arguments and second access two arguments.
Car.javapackage com.concretepage; public class Car < private Integer carId; private String carName; private Car()<>private Car(Integer carId, String carName) < this.carId = carId; this.carName = carName; >public Integer getCarId() < return carId; >public String getCarName() < return carName; >>Here we will show two ways to instantiate a class accessing private constructor using Reflection API.
1. Find the private constructor for given number of arguments and types and instantiate the class.
2. Find the private constructor using given constructor name and instantiate the class.Find the example.
PrivateConstructorDemo.javapackage com.concretepage; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; public class PrivateConstructorDemo < //Find the private constructor for given number of arguments and types and instantiate the class. public void craeteObject(int id, String name) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException < Constructor<?>[] constructors = Car.class.getDeclaredConstructors(); for (Constructor<?> constructor : constructors) < if (Modifier.isPrivate(constructor.getModifiers())) < constructor.setAccessible(true); Class<?>[] clazzs = constructor.getParameterTypes(); if (constructor.getParameterCount() == 2 && clazzs[0] == Integer.class && clazzs[1] == String.class) < Object ob = constructor.newInstance(id, name); if (ob instanceof Car) < Car car = (Car)ob; System.out.println("Car Id:"+ car.getCarId()); System.out.println("Car Name:"+ car.getCarName()); >> > > > //Find the private constructor using given constructor name and instantiate the class. public void craeteObjectByConstructorName(int id, String name) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException < Constructor<Car> constructor = Car.class.getDeclaredConstructor(Integer.class, String.class); if (Modifier.isPrivate(constructor.getModifiers())) < constructor.setAccessible(true); Car car = (Car)constructor.newInstance(id, name); System.out.println("Car Id:"+ car.getCarId()); System.out.println("Car Name:"+ car.getCarName()); >> public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException < PrivateConstructorDemo ob = new PrivateConstructorDemo(); ob.craeteObject(10, "Alto"); System.out.println("-------------------------"); ob.craeteObjectByConstructorName(20,"Santro"); >>Class.getDeclaredConstructors(): It returns an array of Constructor of a class that can be public, protected or private constructor.
Constructor: It gives the information of a class constructor.
constructor.setAccessible(): When it is set true, it allows to access private constructor.
constructor.newInstance(): The class is instantiated by using the calling constructor. We need to pass required parameters.Car Id:10 Car Name:Alto ------------------------- Car Id:20 Car Name:Santro