get Field Value via reflection - Java Reflection

Java examples for Reflection:Field Value

Description

get Field Value via reflection

Demo Code


import java.lang.reflect.Field;

public class Main{

    @SuppressWarnings("unchecked")
    public static <T> T getFieldValue(Object bean, String name) {
        Field field;//from   w  w  w  . j  a v a  2 s. c  o  m
        T result = null;
        try {
            field = bean.getClass().getDeclaredField(name);
            field.setAccessible(true);
            result = (T) field.get(bean);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    @SuppressWarnings("unchecked")
    public static <T> T getFieldValue(Object bean, Field field) {
        T result = null;
        try {
            field.setAccessible(true);
            result = (T) field.get(bean);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

Related Tutorials