tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > Reflection > Field Info

Field Info 

The following example shows how to access field information of a given class.

File Name  :  
com/bethecoder/tutorials/reflection/FieldInfo.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.reflection;

import java.lang.reflect.Field;

public class FieldInfo {

  /**
   @param args
   */
  public static void main(String[] args) {

    //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 = ; 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



 
  


  
bl  br