首页 > 系统 > Android > 正文

java反射android的r文件的示例

2020-04-11 11:51:43
字体:
来源:转载
供稿:网友

动态取得R文件的int值,通过string-array name属性动态获取R.array.xxx的int值

复制代码 代码如下:

//通过string-array name属性动态获取R.array.xxx的int值
public CharSequence[] getListData(String name) {
        try {
            Class<?> arrayClass = getArrayResource().getClass();
            Field intField = arrayClass.getField(name);
            int sourceId = intField.getInt(name);
            return getResources().getTextArray(sourceId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

private Object arrayResource = null;

private Object getArrayResource() {
        if (arrayResource == null) {
            Class<?> resource = R.class;
            try {
                Class<?>[] classes = resource.getClasses();
                for (Class<?> c : classes) {
                    int i = c.getModifiers();
                    String className = c.getName();
                    String s = Modifier.toString(i);
                    if (s.contains("static") && className.contains("array")) {
                        return c.getConstructor().newInstance();
                    } else {
                        continue;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return arrayResource;
    }

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表