Read Field
Apache Commons Lang 3.0 is a java library with lot of utilities and reusable components.
This requires the library commons-lang3-3.0.1.jar to be in classpath.
The following example shows using FieldUtils.readField() API.
It returns the value of named field by considering the specified class and its super classes.
package com.bethecoder.tutorials.commons_lang.common;
public class Student extends Person {
private static String DEFAULT_NAME = "Unknown" ;
private String name;
private int age;
private String hobby;
public Student () {
}
public Student ( String name, int age, String hobby ) {
super () ;
this .name = name;
this .age = age;
this .hobby = hobby;
}
public String getName () {
return name;
}
public void setName ( String name ) {
this .name = name;
}
public int getAge () {
return age;
}
public void setAge ( int age ) {
this .age = age;
}
public String getHobby () {
return hobby;
}
public void setHobby ( String hobby ) {
this .hobby = hobby;
}
public String toString () {
return "Student[name = " + name + ", age = " + age + ", hobby = " + hobby + "]" ;
}
}
package com.bethecoder.tutorials.commons_lang.tests.reflections;
import org.apache.commons.lang3.reflect.FieldUtils;
import com.bethecoder.tutorials.commons_lang.common.Student;
public class ReadFieldTest {
/**
* @param args
* @throws IllegalAccessException
* @throws IllegalAccessException
*/
public static void main ( String [] args ) throws IllegalAccessException {
Student std = new Student ( "Sriram" , 2 , "Chess" ) ;
String name = ( String ) FieldUtils.readField ( std, "name" , true ) ;
System.out.println ( name ) ;
Integer age = ( Integer ) FieldUtils.readField ( std, "age" , true ) ;
System.out.println ( age ) ;
}
}
It gives the following output,
Sriram
2