如何在没有库的情况下获取所有扩展类
在我的项目中,我有一个类City
和其他扩展它的类(伦敦
,paris
...)。我想实例化所有扩展city
(城市的子类)的类,而无需使用任何外部库。
我想避免使用这样的构造函数手动实例化课程:
List<City> cities = new ArrayList<City>();
cities.add( new London() );
cities.add( new California() );
cities.add( new Chicago() );
类:
public abstract Class City{
public abstract String getName();
}
public Class London{
public String getName(){
return "London";
}
}
public Class Paris{
public String getName(){
return "Paris";
}
}
Within my project I have a class City
and other classes that extend it (London
,Paris
...). I want to instantiate all the classes that extend City
(all the subclasses of City) without using any external library.
I want to avoid instantiating classes manually using the constructors like that:
List<City> cities = new ArrayList<City>();
cities.add( new London() );
cities.add( new California() );
cities.add( new Chicago() );
Classes:
public abstract Class City{
public abstract String getName();
}
public Class London{
public String getName(){
return "London";
}
}
public Class Paris{
public String getName(){
return "Paris";
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个解决方案,可以正常工作,但是您可以添加一些增强功能(使其与间接超级类别一起使用。.),这个想法是:查找项目目录中的所有类(按名称)。在此之后,实现了所有这些类:
输出
图像阐明文件路径和Java类的内容

从另一个堆栈答案中复制了一些代码,然后从这里进行: https://dzone.com/articles/get-all-classes-within package 。
This is a solution,it works but you can add some enhancement (make it work with indirect superClasses ..), the idea is : find all the classes in the project directory , iterate those classes and look for all classes that extends a given class (by name). After that instanciate all these classes :
Output
Image to clarify the path of files and the content of java classes

some code is copied from another stack answer and from here : https://dzone.com/articles/get-all-classes-within-package.