是否可以使用反射遍历包内的所有类? [英] Is possible iterate over all classes inside a package with Reflection?

查看:33
本文介绍了是否可以使用反射遍历包内的所有类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有一定价值的字符串.我想遍历调用特定方法的包中的所有类,如果该方法返回的值等于我的 String 中的值,则创建该类的对象.

I have a String with some value. I want to iterate over all classes in a package calling a specific method, and if the value returned by the method is equals the value in my String, create an object of that class.

我想以动态方式执行此操作,因此如果我在此包中添加一个类,它将自动在迭代中.

I want do this in a dynamic way, so if I add a class in this package, it will automatically be in the iteration.

可以这样做吗?如果没有,有没有办法做我想做的事?

我期待类似的东西.

for(Class clazz: SomeClass.listClasses("org.package")){
     //code here
}

推荐答案

不,这不可能以完全可靠的方式进行;然而,在许多情况下实施起来可能是实用的.

No, this is not possible in a totally reliable way; however, it may be practical to implement in many cases.

由于 Java 类加载器的灵活性,在特定包下定义的类在运行时可能是未知的(例如考虑一个特殊的类加载器,它动态定义类,可能通过从网络加载它们,或编译他们是临时的).因此,没有标准的 Java API 允许您列出包中的类.

Due to the flexibility of Java class loaders, the classes defined under a particular package may not be known at runtime (e.g. consider a special classloader which defines classes on-the-fly, perhaps by loading them from the network, or compiling them ad-hoc). As such, there is no standard Java API which allows you to list the classes in a package.

然而,实际上,您可以通过搜索所有类和 JAR 文件的类路径、构建完全限定类名的集合并根据需要进行搜索来实现一些技巧.如果您确定没有活动的类加载器会像上一段中描述的那样运行,则此策略会正常工作.例如(Java 伪代码):

Practically speaking, however, you could do some tricks by searching the classpath for all class and JAR files, building a collection of fully-qualified class names, and searching them as desired. This strategy would work fine if you are sure that no active classloader will behave as described in the previous paragraph. For example (Java pseudocode):

Map<String, Set<String>> classesInPackage = new HashMap();
for (String entry : eachClasspathEntry()) {
  if (isClassFile(entry)) {
    String packageName = getPackageName(entry);
    if (!classesInPackage.containsKey(packageName)) {
      classesInPackage.put(packageName, new HashSet<String>());
    }
    classesInPackage.get(packageName).add(getClassName(entry));
  } else if (isJarOrZipFile(entry)) {
    // Do the same for each JAR/ZIP file entry...
  }
}
classesInPackage.get("com.foo.bar"); // => Set<String> of each class...

这篇关于是否可以使用反射遍历包内的所有类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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