Reputation: 3672
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.
Upvotes: 2
Views: 4598
Reputation: 918
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;
Upvotes: 4
Reputation: 2051
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.
Upvotes: 3
Reputation: 2523
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.
Upvotes: 2