In this tutorial we are going to learn how to get all fields of a class . To get fields of a class , getDeclaredFields() method was provided in java.lang.Class class . See the below example for better understanding .

package com.java;
import java.lang.reflect.Field;

class Sample 
{
    int a ;
    String name ;
    public static void main(String[] args) throws Exception
    {
        Class c1 = Class.forName("com.java.Sample");
        Field f[] = c1.getDeclaredFields();
        for(Field fl:f)
        {
            String fname = fl.getName();
            Class c2 = fl.getType();
            String typename = c2.getName();
            System.out.println("Field name is : "+fname+"  and type is : "+typename);
        }
    }
}


/* 

Output :

Field name is : a  and type is : int
Field name is : name  and type is : java.lang.String

*/


If we want to get public fields only then we have to use getFields() method . It will all return all public fields from super classes also .