Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set private field value with reflection

I have 2 classes: Father and Child

public class Father implements Serializable, JSONInterface {      private String a_field;      //setter and getter here  }  public class Child extends Father {     //empty class } 

With reflection I want to set a_field in Child class:

Class<?> clazz = Class.forName("Child"); Object cc = clazz.newInstance();  Field f1 = cc.getClass().getField("a_field"); f1.set(cc, "reflecting on life"); String str1 = (String) f1.get(cc.getClass()); System.out.println("field: " + str1); 

but I have an exception:

Exception in thread "main" java.lang.NoSuchFieldException: a_field

But if I try:

Child child = new Child(); child.setA_field("123"); 

it works.

Using setter method I have same problem:

method = cc.getClass().getMethod("setA_field"); method.invoke(cc, new Object[] { "aaaaaaaaaaaaaa" }); 
like image 785
user1066183 Avatar asked Sep 22 '15 12:09

user1066183


People also ask

How do you assign a private variable to a reflection?

If we want to access Private Field and method using Reflection we just need to call setAccessible(true) on the field or method object which you want to access. Class. getDeclaredField(String fieldName) or Class. getDeclaredFields() can be used to get private fields.

How private fields can be called using reflection?

Accessing private fields in Java using reflection In order to access a private field using reflection, you need to know the name of the field than by calling getDeclaredFields(String name) you will get a java. lang. reflect. Field instance representing that field.

Can Java reflection API access private fields and methods of a class?

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.

How do you set a value to a private variable in Java?

We have used the getter and setter method to access the private variables. Here, the setter methods setAge() and setName() initializes the private variables. the getter methods getAge() and getName() returns the value of private variables.


1 Answers

To access a private field you need to set Field::setAccessible to true. You can pull the field off the super class. This code works:

Class<?> clazz = Child.class; Object cc = clazz.newInstance();  Field f1 = cc.getClass().getSuperclass().getDeclaredField("a_field"); f1.setAccessible(true); f1.set(cc, "reflecting on life"); String str1 = (String) f1.get(cc); System.out.println("field: " + str1); 
like image 74
John McClean Avatar answered Sep 19 '22 02:09

John McClean