Java.lang Package Classes

Java Class - getFields() Method



The java.lang.Class.getFields() method returns an array containing Field objects reflecting all the accessible public fields of the class or interface represented by this Class object. If this Class object represents a class or interface with no accessible public 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[] getFields()
                  throws SecurityException

Parameters

No parameter is required.

Return Value

Returns the array of Field objects representing the public fields.

Exception

Throws SecurityException, if a security manager, s, is present and 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.getFields() method.

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

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

      //print accessible public fields
      Field f[] = cls.getFields();
      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 int java.lang.Integer.MIN_VALUE
public static final int java.lang.Integer.MAX_VALUE
public static final java.lang.Class java.lang.Integer.TYPE
public static final int java.lang.Integer.SIZE
public static final int java.lang.Integer.BYTES

❮ Java.lang - Class