get Field Value By Field Name - Android java.lang.reflect

Android examples for java.lang.reflect:Field Value

Description

get Field Value By Field Name

Demo Code


//package com.java2s;
import java.lang.reflect.Field;

public class Main {

    public static Object getFieldValueByFieldName(Object instance,
            String fieldName) {/*from   ww  w.  j  a  va 2s .  com*/
        Field[] fields = instance.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (fieldName.equals(field.getName())) {
                try {
                    return field.get(instance);
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return null;
            }
        }
        return null;
    }
}

Related Tutorials