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" });
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With