如何获得类路径上的软件包和/或类的列表? [英] How do I get a list of packages and/or classes on the classpath?

查看:80
本文介绍了如何获得类路径上的软件包和/或类的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我可以使用ClassLoader来获取已加载的类的列表以及这些类的包。但是我如何获得可以加载的类的列表,即在类路径上呢?

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.

这是为编译器准备的。解析foo.bar.Baz时,我想知道foo是否是一个可将其与其他产品区分开的包。

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...


  1. 看看您的类路径

  2. 如果要处理目录,则可以查找以.class结尾的所有文件

  3. 如果要处理jar,请加载该jar并查找所有以.class结尾的文件

  4. 从文件末尾删除.class,将 \替换为。然后您便拥有了完全合格的类名。

  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.

如果您在类路径中使用spring,则可以利用它们来完成大部分操作已经:

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;

这篇关于如何获得类路径上的软件包和/或类的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆