Implementing Spring-like package scanning in Android

后端 未结 5 996
情话喂你
情话喂你 2020-12-30 17:03

I\'m attempting to implement a package-scanning feature, similar to Spring\'s component-scan, for the Android framework I\'m developing. Basically, I would like

5条回答
  •  执笔经年
    2020-12-30 17:33

    I wanted to find all the subclass at runtime. So I've been looking for android class scanning. This is my final code from what I gathered in web. You will get the idea.

    public static void findSubClasses(Context context, Class parent) {
        ApplicationInfo ai = context.getApplicationInfo();
        String classPath = ai.sourceDir;
        DexFile dex = null;
        try {
            dex = new DexFile(classPath);
            Enumeration apkClassNames = dex.entries();
            while (apkClassNames.hasMoreElements()) {
                String className = apkClassNames.nextElement();
                try {
                    Class c = context.getClassLoader().loadClass(className);
                    if (parent.isAssignableFrom(c)) {
                        android.util.Log.i("nora", className);
                    }
                } catch (ClassNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                //              android.util.Log.i("nora", className);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                dex.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    

提交回复
热议问题