Java.lang.Class.getDeclaredField() Method

Advertisements


Description

The java.lang.Class.getDeclaredField() method returns a Field object that reflects the specified declared field of the class or interface represented by this Class object. The name parameter is a String that specifies the simple name of the desired field.

Declaration

Following is the declaration for java.lang.Class.getDeclaredField() method

public Field getDeclaredField(String name) throws NoSuchFieldException, SecurityException

Parameters

  • name -- This is the name of the field.

Return Value

This method returns the Field object for the specified field in this class.

Exception

  • NoSuchFieldException -- If a field with the specified name is not found.

  • NullPointerException -- If name is null.

  • SecurityException -- If a security manager, s, is present.

Example

The following example shows the usage of java.lang.Class.getDeclaredField() method.

package com.tutorialspoint;

import java.lang.reflect.*;

public class ClassDemo {

   public static void main(String[] args) {

     try {            
        ClassDemo c = new ClassDemo();
        Class cls = c.getClass();

        // field long l
        Field lVal  = cls.getDeclaredField("l");
        System.out.println("Field = " + lVal.toString());
     }
     catch(Exception e) {
        System.out.println(e.toString());
     }
   }

   public ClassDemo() {
      // no argument constructor
   }

   public ClassDemo(long l) {
      this.l = l;
   }

   long l = 77688;
}

Let us compile and run the above program, this will produce the following result:

Field = long ClassDemo.l



Advertisements
Advertisements