我有一个父类(super class)
class Geometry{
}
以及扩展它的两个类:
class ShapeOne extends Geometry{}
class ShapeTwo extends Geometry{}
我想要实现的是生成一个类型为 ShapeOne
的对象列表(从数据库中读取)或 ShapeTwo
或任何其他 Geometry
的实例,但动态地将类型作为参数传递,
例如:
public ArrayList< Geometry Object > getList(/**passing typeof generated list**/){
// getting data from Database;
return new ArrayList<typeof generated list>();
}
so the call would be then like:
getList(ShapeTwo);
感谢您的帮助:)
最佳答案
你不能那样做。由于type erasure , List<Geometry>
不是 List<ShapeOne>
的父类(super class).这在此处得到了更好的解释:Is List<Dog> a subclass of List<Animal>? Why aren't Java's generics implicitly polymorphic? .
解决您问题的一些替代方案:
- 返回
List<ShapeOne>
或List<ShapeTwo>
或List<TheExpectedClass>
而不是List<Geometry>
. - 返回
<T extends Geometry> List<T>
并通过Class<T> clazz
作为论据。可能您需要使用附加参数来识别从数据库中恢复的数据是否属于Geometry
的特定子类。 .
关于java - 在java中生成动态类型的数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27302614/