In this example we shall explain with a simple example to get the fields of a class using the reflection. You can list the public and private fields of an object using the following steps:
- Get the Class instance of the class which you want to list the fields. In this example get the Class instance of Math class.
- Call getFields() method from the Class instance which returns the Field[] array which contains the public fields.
- Call getDeclaredFields() method from the Class instance which returns the Field[] array which contains all the fields whether it is private, public or default.
Lets look at this example to list of fields of java.lang.Math class:
[code lang=”java”] package javabeat.net.reflection;import java.lang.reflect.Field;
public class JavaBeatReflectionExample {
public static void main(String[] args) throws Exception {
// Get the Class instance for Math
Class<?> mathClass = java.lang.Math.class;
//Declare Fields class
Field[] refFields;
// List all the public fields in the Math class
refFields = mathClass.getFields();
for (int i = 0; i < refFields.length; i++) {
System.out.println("Public Field: " + refFields[i]);
}
System.out.println();
// List all the fields in the Math class
refFields = mathClass.getDeclaredFields();
for (int i = 0; i < refFields.length; i++) {
System.out.println("Field: " + refFields[i]);
}
}
}
[/code]
Output
[code] Public Field: public static final double java.lang.Math.EPublic Field: public static final double java.lang.Math.PI
Field: public static final double java.lang.Math.E
Field: public static final double java.lang.Math.PI
Field: private static java.util.Random java.lang.Math.randomNumberGenerator
Field: private static long java.lang.Math.negativeZeroFloatBits
Field: private static long java.lang.Math.negativeZeroDoubleBits
[/code]