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.
Its a bit tricky and there are a few libraries that can help, but basically...
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;