Java Reflection - Java Class.getDeclaredField(String name)








Syntax

Class.getDeclaredField(String name) has the following syntax.

public Field getDeclaredField(String name)   throws NoSuchFieldException ,    SecurityException

Example

In the following code shows how to use Class.getDeclaredField(String name) method.

/*  w w  w.  j  a  v  a 2s  .  c  o m*/
import java.lang.reflect.Field;

public class Main {

  public static void main(String[] args) {

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

      Field lVal = cls.getDeclaredField("l");
      System.out.println("Field = " + lVal.toString());
    } catch (Exception e) {
      System.out.println(e.toString());
    }
  }
}
class MyClass{
  public MyClass() {
    // no argument constructor
  }

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

  long l = 123L;
}

The code above generates the following result.