Java.lang.Class.getField() Method



Description

The java.lang.Class.getField() returns a Field object that reflects the specified public member field of the class or interface represented by this Class object. The name parameter is a String specifying the simple name of the desired field.

Declaration

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

public Field getField(String name) throws NoSuchFieldException, SecurityException

Parameters

name − This is the field name.

Return Value

This method returns the Field object of this class specified by name.

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.getField() method.

package com.tutorialspoint;

import java.lang.reflect.*;

public class ClassDemo {

   public static void main(String[] args) {
 
      ClassDemo c = new ClassDemo();
      Class cls = c.getClass();

      System.out.println("Field =");

      try {
         // string field
         Field sField = cls.getField("string1");
         System.out.println("Public field found: " + sField.toString());
      } catch(NoSuchFieldException e) {
         System.out.println(e.toString());
      }
   }

   public ClassDemo() {
      // no argument constructor
   }

   public ClassDemo(String string1) {       
      this.string1 = string1;
   }
    
   public String string1 = "tutorialspoint";
} 

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

Field =
Public field found: public java.lang.String ClassDemo.string1
java_lang_class.htm
Advertisements