Java Reflection - Java Class.getField(String name)








Syntax

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

public Field getField(String name)  throws NoSuchFieldException ,   SecurityException

Example

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

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

public class Main {
  public static void main(String[] args) throws Exception {

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

    Field sField = cls.getField("string1");
    System.out.println("Public field found: " + sField.toString());
  }
}

class MyClass {

  public MyClass() {
  }

  public MyClass(String string1) {
    this.string1 = string1;
  }

  public String string1 = "tutorialspoint";
}

The code above generates the following result.