Java反射 - 获取包列表 [英] Java Reflection - Get List of Packages

查看:98
本文介绍了Java反射 - 获取包列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个包含许多不同包的Java应用程序。我希望能够以编程方式告诉应用程序中存在哪些软件包以特定的预修复程序开头。无论如何使用Java反射API执行此操作?我没有看到与反射apis相关的任何内容。

I am building a Java app that has a number of different packages. I want to be able to tell programmatically which packages exist in the app that start with a specific pre-fix. Is there anyway to do this with the Java reflection APIs? I didn't see anything like this related to the reflection apis.

示例:

com.app.controls.text
com.app.controls.picker
com.app.controls.date
etc

我想通过知道前缀com.app.controls并了解将来可能集成新包来枚举所有这些。

I want to enumerate all of these by knowing the prefix "com.app.controls" and understanding that a new package might get integrated in the future.

谢谢!

推荐答案

你可以使用 Package.getPackages() ,返回当前类加载器已知的所有包的数组。你必须手动循环遍历数组,并使用 getName()

You can do this by using Package.getPackages(), which returns an array of all packages known to the current class loader. You'll have to manually loop through the array and find the ones with the appropriate prefix using getName().

这是一个简单的例子:

public List<String> findPackageNamesStartingWith(String prefix) {
    return Package.getPackages().stream()
        .map(Package::getName)
        .filter(n -> n.startsWith(prefix))
        .collect(toList());
}

请注意,此技术仅返回当前类加载器中定义的包。如果你需要来自不同类加载器的包,有一些选项:

Note that this technique will only return the packages defined in the current class loader. If you need the packages from a different class loader, there are some options:


  1. 安排一些事情,以便你的程序可以运行从类加载器里面的代码。这需要某个组织到您的代码库,这可能是也可能不可行。

  1. Arrange things so that your program can run the above code from inside that class loader. This requires a certain organisation to your code base, which may or may not be feasible.

使用反射来调用(通常受保护的)方法 getPackages()类加载器。如果程序在安全管理器下运行,这将不起作用。

Use reflection to call the (normally protected) method getPackages() on the appropriate class loader. This won't work if the program is running under a security manager.

这篇关于Java反射 - 获取包列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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