CodesJava

Easy learning with example program codes

Java reflection get set public field value


The java.lang.Class provides the methods to examine the runtime properties of the object including its members and type information. For every type of object, the JVM instantiates an immutable instance of java.lang.Class. Using reflection, we can get the metadata of a class at run time.

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

Example

TestClass.java

package com.codesjava;
 
public class TestClass {
	public 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.getField("testField");
			System.out.println(field.get(testClass));
			field.setInt(testClass, 50);
			System.out.println(field.get(testClass));
		} catch (Exception e) {
			e.printStackTrace();
		}  
	}
}

Output

20
50


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap