Java reflection get set private field value

The get() and set() method are used to get and set public field value in java.

Note: We have to turn off the java access check for field modifiers.

Example

TestClass.java

package com.w3spoint;
 
public class TestClass {
	private int testField = 20;
}

ReflectionTest.java

package com.w3spoint;
 
import java.lang.reflect.Field;
 
public class ReflectionTest {
	public static void main(String args[]){
		try {
			TestClass testClass = new TestClass();
			Class c=Class.forName("com.w3spoint.TestClass");  
			Field field = c.getDeclaredField("testField");
			field.setAccessible(true);
			System.out.println(field.get(testClass));
			field.setInt(testClass, 50);
			System.out.println(field.get(testClass));
		} catch (Exception e) {
			e.printStackTrace();
		}  
	}
}

Output

20
50
Please Share