get Property value from an object - Android java.lang.reflect

Android examples for java.lang.reflect:Field Value

Description

get Property value from an object

Demo Code


//package com.java2s;

import java.lang.reflect.Field;

public class Main {
    public static Object getProperty(Object owner, String fieldName)
            throws SecurityException, NoSuchFieldException,
            IllegalArgumentException, IllegalAccessException {
        final Class<?> ownerClass = owner.getClass();
        final Field field = ownerClass.getField(fieldName);
        final Object property = field.get(owner);
        return property;
    }//from w  ww . j  a v  a2 s  .c o  m

    public static Field getField(Field[] fields, String fieldName)
            throws Exception {
        Field f = null;

        for (Field lf : fields) {
            String currentFieldName = lf.getName();
            if (currentFieldName.equals(fieldName)) {
                f = lf;
                break;
            }
        }

        if (f == null)
            throw new Exception(new String(fieldName + " field not found!"));

        return f;
    }
}

Related Tutorials