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

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.