Home » Java programming language

Java Class class getDeclaredField() method with example

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

Class class getDeclaredField() method

  • getDeclaredField() method is available in java.lang package.
  • getDeclaredField() method is used to return a Field objects that indicate the given declared field of the class or an interface denoted by this Class object.
  • getDeclaredField() 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.
  • getDeclaredField() method may throw an exception at the time of returning a Field object.
    • NoSuchFieldException: In this exception when a specifying field does not exists.
    • SecurityException: In this exception it may raise when security manager exists.
    • NullPointerException: In this exception when the given Field is null.

Syntax:

    public Field getDeclaredField (String field_name);

Parameter(s):

  • String field_name – represents the name of the field.

Return value:

The return type of this method is Field, it returns Field object of the given Field in this Class.

Example:

// Java program to demonstrate the example 
// of Field getDeclaredField (String field_name) method of Class 

import java.lang.reflect.*;

public class GetDeclaredFieldOfClass {
    public static void main(String[] args) throws Exception {
        GetDeclaredFieldOfClass declare_field = new GetDeclaredFieldOfClass();
        // Get Class
        Class cl = declare_field.getClass();

        // By using getDeclaredField() method is to get the field of
        // the class 
        Field f = cl.getDeclaredField("i");
        System.out.println("Declared Field: " + f.toString());
    }

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

    // Public Constructors
    public GetDeclaredFieldOfClass(int i) {
        this.i = i;
    }
    int i = 100;
}

Output

We are in private constructor
Declared Field: int GetDeclaredFieldOfClass.i


Comments and Discussions!

Load comments ↻





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