Get a field value from the field name in Java

Description

The following code shows how to get a field value from the field name.

Example


//from www. ja  v a  2 s .c  o  m
import java.lang.reflect.Field;

public class Main {
  public static void main(String[] args) throws Exception {
    Object clazz = new TestClass();
    String lookingForValue = "firstValue";

    Field field = clazz.getClass().getField(lookingForValue);
    Class clazzType = field.getType();
    if (clazzType.toString().equals("double"))
      System.out.println(field.getDouble(clazz));
    else if (clazzType.toString().equals("int"))
      System.out.println(field.getInt(clazz));
    
    //System.out.println(field.get(clazz));
  }
}

class TestClass {
  public double firstValue = 3.14;
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Reflection »




Annotation
Array
Class
Constructor
Field
Generics
Interface
Method
Modifier
Package
Proxy