Java Reference
In-Depth Information
Solution
You can't, in the general case. There are some limited approaches, most involving “classpath
scanning.”
Discussion
There is no way to find out all the classes in a package, in part because, as we just saw in
Constructing a Class from Scratch with a ClassLoader , you can add classes to a package at
any time! And, for better or for worse, the JVM and standard classes such as
java.lang.Package do not even allow you to enumerate the classes currently in a given
package.
The nearest you can come is to look through the classpath. And this will surely work only for
local directories and JAR files; if you have locally defined or network-loaded classes, this is
not going to help. In other words, it will find compiled classes, but not dynamically loaded
ones. There are several libraries that can automate this for you, and you're welcome to use
them. The code to scan the classpath is fairly simple at heart, though, so classy developers
with heart will want to examine it. Example 23-12 shows my ClassesInPackage class with
its one static method. The code works but is rather short on error handling, and will crash on
non-existent packages and other failures.
The code goes through a few gyrations to get the classpath as an enumeration of URLs, then
looks at each element. “file:” URLs will contain the pathname of the file containing the
.class file, so we can just list it. “jar:” URLs contain the filename as “file:/
path_to_jar_file!package/name,” so we have to pull this apart; the “package name” suffix is
slightly redundant in this case because it's the package we asked the ClassLoader to give us.
Example 23-12. ClassesInPackage.java
public
public class
class ClassesInPackage
ClassesInPackage {
/** This approach began as a contribution by Paul Kuit at
* http://stackoverflow.com/questions/1456930/, but his only
* handled single files in a directory in classpath, not in Jar files.
* N.B. Does NOT handle system classes!
* @param packageName
* @return
* @throws IOException
*/
public
public static
static String [] getPackageContent ( String packageName )
throws
throws IOException {
Search WWH ::




Custom Search