Here we are going to write a program, how to get the Field Information using Java Reflection mechanism.
Get Field Information :
[java]
package com.onlinetutorialspoint.ref;
import java.lang.reflect.Field;
public class Reflection_Class_field_Info {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("PLEASE PASS THE CLASS NAME..!");
} else {
try {
Class c = Class.forName(args[0]);
printFields(c);
} catch (ClassNotFoundException cnfe) {
System.out.println(args[0] + "NOT FOUND…");
}
}
}
static void printFields(Class c) {
Field f[] = c.getFields();
System.out.println("NUMBER OF FIELDS : " + f.length);
for (int i = 0; i < f.length; i++) {
String fname = f[i].getName();
Class s = f[i].getType();
String ftype = s.getName();
System.out.println(ftype + " " + fname);
}
}
}
[/java]
Output :
javac Reflection_Class_field_Info.java java Reflection_Class_field_Info java.lang.reflect.Field NUMBER OF FIELDS : 2 int PUBLIC int DECLARED
Happy Learning 🙂