How do I get a list of packages and/or classes on the classpath?

我们两清 提交于 2019-12-03 20:57:44

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;

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!