CodesJava

Easy learning with example program codes

Java reflection get set public field value


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
Please follow and like us:


Copyright © 2019 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki