Java.lang Package Classes

Java Class - getDeclaredFields() Method



The java.lang.Class.getDeclaredFields() method returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object. This includes public, protected, default (package) access, and private fields, but excludes inherited fields.

If this Class object represents a class or interface with no declared fields, then this method returns an array of length 0. If this Class object represents an array type, a primitive type, or void, then this method returns an array of length 0.

Syntax

public Field[] getDeclaredFields()
                          throws SecurityException

Parameters

No parameter is required.

Return Value

Returns the array of Field objects representing all the declared fields of this class.

Exception

Throws SecurityException, if a security manager, s, is present and any of the following conditions is met:

  • the caller's class loader is not the same as the class loader of this class and invocation of s.checkPermission method with RuntimePermission("accessDeclaredMembers") denies access to the declared fields within this class.
  • the caller's class loader is not the same as or an ancestor of the class loader for the current class and invocation of s.checkPackageAccess() denies access to the package of this class.

Example:

The example below shows usage of the java.lang.Class.getDeclaredFields() method.

import java.lang.*;
import java.lang.reflect.*;

public class MyClass {
  public static void main(String[] args) {
    try {
      Class cls = Class.forName("java.lang.Boolean");

      //print accessible public methods
      Field f[] = cls.getDeclaredFields();
      System.out.println("Fields are: ");
      for(Field i: f)
        System.out.println(i);
        
    } catch (Exception e) {
      System.out.println(e);
    }
  }
}

The output of the above code will be:

Fields are: 
public static final java.lang.Boolean java.lang.Boolean.TRUE
public static final java.lang.Boolean java.lang.Boolean.FALSE
public static final java.lang.Class java.lang.Boolean.TYPE
private final boolean java.lang.Boolean.value
private static final long java.lang.Boolean.serialVersionUID

❮ Java.lang - Class