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

帅比萌擦擦* 提交于 2020-01-01 06:54:07

问题


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.


回答1:


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;



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/1308961/how-do-i-get-a-list-of-packages-and-or-classes-on-the-classpath

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