在运行时,查找扩展基类的Java应用程序中的所有类 [英] At runtime, find all classes in a Java application that extend a base class

查看:88
本文介绍了在运行时,查找扩展基类的Java应用程序中的所有类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情:

  List< Animal> animals = new ArrayList< Animal>(); 

for(Class c:list_of_all_classes_available_to_my_app())
if(c is Animal)
animals.add(new c());

所以,我想查看应用程序世界中的所有类,当我找到一个类时从Animal下载,我想创建该类型的新对象并将其添加到列表中。这允许我添加功能而无需更新事物列表。我可以避免以下情况:

  List< Animal> animals = new ArrayList< Animal>(); 
animals.add(new Dog());
animals.add(新猫());
animals.add(new Donkey());
...

通过上述方法,我可以简单地创建一个扩展的新类动物,它会被自动捡起。



更新时间:2008年10月16日上午9:00太平洋标准时间:



这个问题引起了很多很好的回应 - 谢谢。从回答和我的研究中,我发现我真正想要做的就是在Java下不可能。有一些方法,比如ddimitrov的ServiceLoader机制可以工作 - 但它们对我想要的东西非常重,我相信我只是将问题从Java代码转移到外部配置文件。



另一种表达我想要的方式:我的Animal类中的静态函数查找并实例化从Animal继承的所有类 - 无需任何进一步的配置/编码。如果我必须配置,我也可以在Animal类中实例化它们。我理解,因为Java程序只是一个松散的.class文件联盟,就像它一样。



有趣的是,它似乎是相当简单

org.reflections :

 思考反射=新思考(com.mycompany); 
设置< Class<?扩展MyInterface>> classes = reflections.getSubTypesOf(MyInterface.class);


I want to do something like this:

List<Animal> animals = new ArrayList<Animal>();

for( Class c: list_of_all_classes_available_to_my_app() )
   if (c is Animal)
      animals.add( new c() );

So, I want to look at all of the classes in my application's universe, and when I find one that descends from Animal, I want to create a new object of that type and add it to the list. This allows me to add functionality without having to update a list of things. I can avoid the following:

List<Animal> animals = new ArrayList<Animal>();
animals.add( new Dog() );
animals.add( new Cat() );
animals.add( new Donkey() );
...

With the above approach, I can simply create a new class that extends Animal and it'll get picked up automatically.

UPDATE: 10/16/2008 9:00 a.m. Pacific Standard Time:

This question has generated a lot of great responses -- thank you. From the responses and my research, I've found that what I really want to do is just not possible under Java. There are approaches, such as ddimitrov's ServiceLoader mechanism that can work -- but they are very heavy for what I want, and I believe I simply move the problem from Java code to an external configuration file.

Another way to state what I want: a static function in my Animal class finds and instantiates all classes that inherit from Animal -- without any further configuration/coding. If I have to configure, I might as well just instantiate them in the Animal class anyway. I understand that because a Java program is just a loose federation of .class files that that's just the way it is.

Interestingly, it seems this is fairly trivial in C#.

解决方案

I use org.reflections:

Reflections reflections = new Reflections("com.mycompany");    
Set<Class<? extends MyInterface>> classes = reflections.getSubTypesOf(MyInterface.class);

这篇关于在运行时,查找扩展基类的Java应用程序中的所有类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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