Write a java program to print fields or data members of a class?



import java.lang.reflect.Field;
class Fields {
 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);
  }
 }
}
class FieldsDemo {
 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]);
    Fields fs = new Fields();
    fs.printFields(c);
   } catch (ClassNotFoundException cnfe) {
    System.out.println(args[0] + "NOT FOUND");
   }
  }
 }
}


No comments:

Post a Comment