//Gets all public fields (including static) from the class
Field [] fields = FieldCls.class.getFields();
show(fields);
System.out.println("##############################");
//Gets all fields (including static) declared in the class
//irrespective of the visibility
fields = FieldCls.class.getDeclaredFields();
show(fields);
}
private static void show(Field [] fields) {
System.out.println("Total fields : " + fields.length); for (int i = 0 ; i < fields.length ; i ++) {
System.out.println(fields[i]);
}
}
}
class FieldCls {
private int a; int b; protected int c; public int d;
private static int a2; static int b2; protected static int c2; public static int d2;
}
It gives the following output,
Total fields : 2
public int com.bethecoder.tutorials.reflection.FieldCls.d
public static int com.bethecoder.tutorials.reflection.FieldCls.d2
##############################
Total fields : 8
private int com.bethecoder.tutorials.reflection.FieldCls.a
int com.bethecoder.tutorials.reflection.FieldCls.b
protected int com.bethecoder.tutorials.reflection.FieldCls.c
public int com.bethecoder.tutorials.reflection.FieldCls.d
private static int com.bethecoder.tutorials.reflection.FieldCls.a2
static int com.bethecoder.tutorials.reflection.FieldCls.b2
protected static int com.bethecoder.tutorials.reflection.FieldCls.c2
public static int com.bethecoder.tutorials.reflection.FieldCls.d2