Get Fields using Reflection

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:

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]);
		}

	}
}

Output

Public Field: public static final double java.lang.Math.E
Public 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

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*