Home » Java programming language

Java Class class getFields() method with example

Class class getFields() method: Here, we are going to learn about the getFields() method of Class class with its syntax and example.
Submitted by Preeti Jain, on November 14, 2019

Class class getFields() method

  • getFields() method is available in java.lang package.
  • getFields() method is used to return an array of Field objects that indicate all the public Fields of the class or interface denoted by this Class object.
  • getFields() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • getFields() method may throw an exception at the time of returning an array of Field objects.
    SecurityException: In this exception, it may raise when the security manager exists.

Syntax:

    public Field[] getFields();

Parameter(s):

  • It does not accept any parameter.

Return value:

The return type of this method is Field[], it returns an array of Field object denoting all the public field of this class or an interface.

Note:

  • When class or interface does not contain public field, 0 is returned.
  • When this class object holds primitive, an array class, or void type, 0 is returned.

Example:

// Java program to demonstrate the example 
// of Field[] getFields () method of Class 

import java.lang.reflect.*;

public class GetFieldsOfClass {
    public static void main(String[] args) throws Exception {
        GetFieldsOfClass fields = new GetFieldsOfClass();

        // Get Class
        Class cl = fields.getClass();

        // It returns an array of Field objects that indicate
        // public fields represented by the Class
        Field[] f = cl.getFields();

        for (int i = 0; i < f.length; ++i)
            System.out.println("Public Fields: " + f[i].toString());
    }

    // Private Constructors
    private GetFieldsOfClass() {
        System.out.println("We are in private constructor");
    }

    // Public Constructors
    public GetFieldsOfClass(int i, short s) {
        this.i = i;
        this.s = s;
    }

    private int i = 100;
    public short s = 200;
}

Output

We are in private constructor
Public Fields: public short GetFieldsOfClass.s


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.