We can get or set a field using reflection in two steps.
Static and instance fields are accessed the same way.
import java.lang.reflect.Field; //from ww w. j a va 2s . co m class MyClass { public String name = "Unknown"; public MyClass() { } public String toString() { return "name=" + this.name; } } public class Main { public static void main(String[] args) { Class<MyClass> ppClass = MyClass.class; try { MyClass p = ppClass.newInstance(); Field name = ppClass.getField("name"); String nameValue = (String) name.get(p); System.out.println("Current name is " + nameValue); name.set(p, "abc"); nameValue = (String) name.get(p); System.out.println("New name is " + nameValue); } catch (InstantiationException | IllegalAccessException | NoSuchFieldException | SecurityException | IllegalArgumentException e) { System.out.println(e.getMessage()); } } }
The code above generates the following result.
To access non-accessible fields, methods, and constructors of a class using reflection
call setAccessible(boolean flag)
method from AccessibleObject
class.
We need to call this method with a true argument to make that field, method, and constructor accessible.
import java.lang.reflect.Field; // ww w .j a v a 2 s . c o m class MyClass { private String name = "Unknown"; public MyClass() { } public String toString() { return "name=" + this.name; } } public class Main { public static void main(String[] args) { Class<MyClass> my = MyClass.class; try { MyClass p = my.newInstance(); Field nameField = my.getDeclaredField("name"); nameField.setAccessible(true); String nameValue = (String) nameField.get(p); System.out.println("Current name is " + nameValue); nameField.set(p, "abc"); nameValue = (String) nameField.get(p); System.out.println("New name is " + nameValue); } catch (InstantiationException | IllegalAccessException | NoSuchFieldException | SecurityException | IllegalArgumentException e) { System.out.println(e.getMessage()); } } }
The code above generates the following result.