Retrieving a list of classes from a package in an

2019-04-06 04:22发布

问题:

I'm aware that it isn't easily feasible to get all of the classes in a package using reflection, but I'm wondering if someone knows of a good solution/workaround, specifically for an Android project?

Given a package, I need to be able to retrieve all of the classes from it and process annotations from them using reflection.

Does anyone know of a way to do this? Are there any libraries available?

回答1:

Existing dependency injection solutions use reflection for processing the annotations, but still need the resources to be declared. See this example of DI using reflection.

If you are using Ant to build your artifacts, you could read the contents of your source directory using Bash or Java, and use this to regenerate the full hierarchy of classes automatically during each build. This might make things tricky if you rely on heavily on the Eclipse IDE though, since the list might be out of date until you run another Ant build. (Note: according to Pyscho you can make Eclipse use Ant by altering the project configuration, see comments)

Another option might be to process the AndroidManifest file using the AssetManager, but you would be limited to the resources declared in that file. The compiled classes themselves are in-lined and optimised in the classes.dex file, and as such you're unlikely to get much useful information from it.



回答2:

Scanning the filesystem as most solutions for non-Android Java do won't help on Android. Here's a (theoretical) solution that is android-specific: http://mindtherobot.com/blog/737/android-hacks-scan-android-classpath/

However, it remains a hack, since Java unfortunately does not directly support this.



回答3:

I think you might find the answer here https://stackoverflow.com/a/1457971/1199538 there is a java file attached so you can download it and try it

short snippet from the answer following:

This method can only be used when:

You have a class that is in the same package you want to discover, This class is called a SeedClass. For example, if you want to list all classes in 'java.io', the seed class may be java.io.File.

Your classes are in a directory or in a JAR file it has source file information (not source code file, but just source file). As far as I've tried, it work almost 100% except the JVM class (those classes come with the JVM).

Your program must have permission to access ProtectionDomain of those classes. If your program is loaded locally, there should be no problem.