CodesJava

Easy learning with example program codes

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.codesjava;
 
public class TestClass {
	private int testField = 20;
}

ReflectionTest.java

package com.codesjava;
 
import java.lang.reflect.Field;
 
public class ReflectionTest {
	public static void main(String args[]){
		try {
			TestClass testClass = new TestClass();
			Class c=Class.forName("com.codesjava.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 follow and like us:
error








Copyright © 2019 CodesJava DMCA.com Protection Status