get Static Int value from Field via Class - Android java.lang.reflect

Android examples for java.lang.reflect:Field Value

Description

get Static Int value from Field via Class

Demo Code


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

public class Main {
    public static int getStaticInt(String clzz, String field, int defaultVal) {
        Field fld = getField(clzz, field);
        if (fld != null) {
            Object obj = getObject(fld, null);
            if (obj != null) {
                try {
                    return (Integer) obj;
                } catch (Exception e) {

                }//from ww w.j  a va2  s  . c o m
            }
        }
        return defaultVal;
    }

    public static Field getField(Class cls, String field) {
        try {
            Field fld = cls.getDeclaredField(field);
            if (fld != null)
                fld.setAccessible(true);
            return fld;
        } catch (Exception e) {
            //if(DEBUG)
            //   Log.e(TAG,e.getMessage(), e);
            return null;
        }
    }

    public static Field getField(String clzz, String field) {
        try {
            Class clazz = Class.forName(clzz);
            if (clazz != null) {
                return getField(clazz, field);
            }
        } catch (Exception e) {

        }
        return null;
    }

    public static Object getObject(Field fld, Object instance) {
        try {
            Object obj = fld.get(instance);
            return obj;
        } catch (Exception e) {
            //if(DEBUG)
            //   Log.e(TAG,e.getMessage(), e);
            return null;
        }
    }
}

Related Tutorials