find Class In R using reflection - Android App

Android examples for App:R

Description

find Class In R using reflection

Demo Code


//package com.java2s;

import java.lang.reflect.Modifier;

public class Main {

    public static Class<?> findClassInR(String packageName, String className) {
        Object obj = findObjInR(packageName, className);
        if (obj != null) {
            return obj.getClass();
        }/* www .  j a  v a 2 s. c  o  m*/
        return null;
    }

    private static Object findObjInR(String packageName, String className) {
        try {
            Class<?> managerClass = Class.forName(packageName + ".R");
            Class<?>[] classes = managerClass.getClasses();
            for (Class<?> c : classes) {
                int i = c.getModifiers();
                String name = c.getName();
                String s = Modifier.toString(i);
                if (s.contains("static") && name.endsWith("$" + className)) {
                    return c.getConstructor().newInstance();
                } else {
                    continue;
                }
            }
        } catch (Exception e) {
        }
        return null;
    }
}

Related Tutorials