Get all declared fields from a class in Java

Description

The following code shows how to get all declared fields from a class.

Example


//from w w w . j a v a 2 s .co m
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Main{
  public static void main(String args[]) throws Exception {
    Class c = Class.forName("MyClass");
    System.out.println("\nFields:");
    Field fields[] = c.getDeclaredFields();
    for (Field fld : fields)
      System.out.println(" " + fld);
  }
}
class MyClass {
  private int count;

  MyClass(int c) {
    count = c;
  }

  MyClass() {
    count = 0;
  }

  void setCount(int c) {
    count = c;
  }

  int getCount() {
    return count;
  }

  void showcount() {
    System.out.println("count is " + count);
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Reflection »




Annotation
Array
Class
Constructor
Field
Generics
Interface
Method
Modifier
Package
Proxy