views:

93

answers:

3

In Java, I can use a ClassLoader to get a list of classes that are already loaded, and the packages of those classes. But how do I get a list of classes that could be loaded, i.e. are on the classpath? Same with packages.

This is for a compiler; when parsing foo.bar.Baz, I want to know whether foo is a package to distinguish it from anything else.

+2  A: 

I have searched for that answer myself, but it is not possible.

The only way I know of is that you have all classes that could be loaded in a specific directory, and then search it for the names of files ending with .class.

After that, you can do Class.forName(name_of_class_file).createInstance() on those file names.

Paxinum
+2  A: 

I think the org.reflections library should do what you want. It scans the classpath and allows you to, for example, get all classes or just those that extend a particular supertype. From there, it should be possible to get all the available packages.

Brett Daniel
+2  A: 

Its a bit tricky and there are a few libraries that can help, but basically...

  1. Look at your classpath
  2. If you are dealing with a directory, you can look for all files ending in .class
  3. If you are dealing with a jar, load the jar up and look for all files ending in .class
  4. Remove the .class from the end of the file, replace the "\" with "." and then you have the fully qualified classname.

If you have spring in your classpath, you can take advantage of them doing most of this already:

ArrayList<String> retval = new ArrayList<Class<?>>();
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(resolver);
String basePath = ClassUtils.convertClassNameToResourcePath("com.mypackage.to.search");
Resource[] resources;
try {
    resources = resolver.getResources("classpath*:" + basePath + "/**/*.class");
} catch (IOException e) {
    throw new AssertionError(e);
}
for (Resource resource : resources) {
    MetadataReader reader;
    try {
        reader = readerFactory.getMetadataReader(resource);
    } catch (IOException e) {
        throw new AssertionError(e);
    }
String className = reader.getClassMetadata().getClassName();
retval.add(className) 
}
return retval;
Eric Anderson