Java Reflection Get Field Information

By |2018-03-21T21:23:50+05:30June 22nd, 2016|java programs|

Here we are going to write a program, how to get the Field Information using Java Reflection mechanism.

Get Field Information :


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

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 🙂

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment