Implementing Spring-like package scanning in Android

后端 未结 5 971
情话喂你
情话喂你 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:47

    EDIT:

    I found this issue in the Android issue tracker. It appears that ClassLoader.getResource(String) is 'working as expected', in that it returns null. This is expected because the DalvikVM does not keep the resources around after compiling. There are workarounds listed in the issue, but there may be another way to access the classes you desire.

    Use the PackageManager to get a hold of an instance of ApplicationInfo. ApplicationInfo has a public field called sourceDir which is the full path (a String) to the location of the source directory for that application. Create a File from this String, and you should be able to navigate to your package within the source directory. Once there, you can use the method from my original answer to find the classes you are looking for.

    String applicationSourceDir = 
        getPackageManager().getApplicationInfo(androidPackageName, 0).sourceDir;
    

    /EDIT

    You should be able to use the ClassLoader.getResource(String) to get a URL to your specific package (the passed in String being the package name you are interested in delimited by path separators rather than periods). With this URL you can then call getFile(), from which you can create a Java File to the package folder. Call packageFile.listFiles() from there, and you have your classes/subpackages.

    Be recursive with the subpackages, and with the classes find the Class object using the static Class.forName(String) method.

提交回复
热议问题