Home  >  Core Java

Example of Field in Reflection API in Java

By Arvind Rai, January 18, 2013
Field in Reflection API is the class to handle the fields of a class. We dynamically can get the information of all fields. We can reset the fields of a class with new values. The method getDeclaredFields returns the array of Fields declared inside the class. The method set can set the values of fields with new value. The method get returns the values of a fields. The class Field is used to deal with the fields of class dynamically.
package com.concretepage.reflection;

public class TestClass {
	
	public static String PAGE_NAME="Atul";
	public static int PAGE_AGE=20;   
	
}
package com.concretepage.reflection;

import java.lang.reflect.Field;

public class ReflectionFieldTest {
	public static void main(String... args) throws ClassNotFoundException, SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException{
		Class<?> c= Class.forName("com.concretepage.reflection.TestClass");
		
		//gets declared fields.
		Field[] field=c.getDeclaredFields();
		for(Field f:field){
			System.out.println(f.getName());
			System.out.println(f.get(f.getName()));
		}
		
		//sets new value to the field
		Field f=c.getDeclaredField("PAGE_NAME");
		f.set(f.getName(), "New Value");
		System.out.println(f.get(f.getName()));
		
	}

}
Output
PAGE_NAME
Atul
PAGE_AGE
20
New Value
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us