set and get Field - Android java.lang.reflect

Android examples for java.lang.reflect:Field

Description

set and get Field

Demo Code


//package com.java2s;
import android.support.annotation.Nullable;
import java.lang.reflect.Field;

public class Main {
    public static void setField(Object obj, String name, Object value) {
        try {/*from   w  w w  .  j ava2 s .c om*/
            Field field = getField(obj.getClass(), name);
            if (field == null) {
                return;
            }
            field.setAccessible(true);
            field.set(obj, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Field getField(Class clazz, String name) {
        try {
            return clazz.getDeclaredField(name);
        } catch (NoSuchFieldException nsfe) {
            return getField(clazz.getSuperclass(), name);
        } catch (Exception e) {
            return null;
        }
    }

    @Nullable
    public static Object getDeclaredField(Object obj, String fieldName) {
        try {
            Field f = getField(obj.getClass(), fieldName);
            if (f == null) {
                return null;
            }
            f.setAccessible(true);
            return f.get(obj);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

Related Tutorials