在 Java 中在运行时获取所有声明的子类? [英] Get all declared subclasses at runtime in Java?

查看:55
本文介绍了在 Java 中在运行时获取所有声明的子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含Device"的所有子类的包,如下所示:

Let's say I have a package that contains all subclasses of 'Device', like this one:

class TV extends Device{

   @override
   public void run() {
       //code goes here
   }

   private void moreMethods(String args){
       // more code
   }

}

在主类中,应该可以通过调用每个人的run"方法在运行时实例化和运行 Device 的每个子类.

In the main class it should be possible to instantiate and run every subclass of Device at runtime by calling everyone's 'run' method.

这样做的好处是允许用户简单地将新的设备文件放入包中,这些文件将自动运行,而无需编辑主类.

The benefit of this is to allow users to simply put new Device files into the package and said files will run automatically without having to edit the main class.

有没有干净的方法来做到这一点?我在想,也许如果我在那个包中有一个包含每个子类名称的 txt 文件,这是可能的.用户必须编辑文件并添加新设备的名称,因此带来了一些不便.

Is there a clean way to do this? I was thinking that maybe if I had a txt file in that package with every subclass name, it would be possible. Minor inconvenience being the user had to edit the file and add the new device's name.

还有其他方法可以达到相同的结果吗?我有兴趣为用户提供一种无需编辑现有代码即可添加新设备文件的方法.

Is there another way to achieve the same result? I'm interested in providing a way for users to add new device files without editing existent code.

推荐答案

如果反射是一个选项,您可以首先找到专用包的所有类 (你能使用反射找到包中的所有类吗?, 如何获取包中的所有类名?),然后使用:

If reflection is an option, you could first find all the classes of the dedicated package (Can you find all classes in a package using reflection?, How to get all classes names in a package?), then use:

for (Class<?> candidateClass : foundClasses) {
    if (Device.class.isAssignableFrom(candidateClass)) {
        candidateClass.newInstance().run();
    }
}

这篇关于在 Java 中在运行时获取所有声明的子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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