Fields

This application asks the Mystery class for all of the public fields (variables) declared within it, along with the data type for each.

import java.lang.reflect.*;

public class ReflectFields {


  public ReflectFields ()  {
    super ();
  }  // end ReflectFields constructor

  
  public static void main ( String [ ] args )  {

    try  {

        Mystery mystery = new Mystery();
        
        Class theClass = Class.forName("Mystery");
        String s = theClass.getName();
        System.out.println("Name of class: " + s);
        System.out.println();

        System.out.println("Fields declared in class: " );
        Field[] theFields = theClass.getDeclaredFields();
        for (int i = 0; i < theFields.length; i++) {
            
            String fieldName = theFields[i].getName();
            System.out.println(i+" Field Name: " + fieldName);
            
            String returnString = theFields[i].getType().getName();
            System.out.println("   Return Type: " + returnString);
            
            Object value = theFields[i].get(mystery);
            System.out.println("   Value: " + value.toString() );
            
            System.out.println();
            System.out.println();
            
        }  // end for: i


    } // end try

    catch ( ClassNotFoundException e ) {
        System.out.println ( "Class not found: " + e );
    }
   catch ( IllegalAccessException e ) {
        System.out.println ( "IllegalAccessException: " + e );
    }


  }  // end main



}  // end ReflectFields