Example of java reflecting android's r file

  • 2020-05-27 07:10:00
  • OfStack

The int value of the R file is dynamically obtained, and the int value of R.array.xxx is dynamically obtained through the string-array name property


// through string-array name Property dynamic acquisition R.array.xxx the int value 
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;
    }


Related articles: