假设有一个名为Entity的接口,有许多类实现它。 我需要创建一个类,对于类的每个实例,它的集合将只包含实现接口实体的对象,但是来自相同的实现类,例如 - 如果Person和Bicycle实现了接口实体,然后该类的实例将只有Person对象或Bicycle对象的集合,但不是两者。 感谢您的帮助!
答案 0 :(得分:0)
public class Something<T extends Entity> {
[...]
private Collection<T> entities;
T
将始终是一个实现Entity
的类。您可以在此类的所有方法中使用T
。
答案 1 :(得分:0)
如果你真的想这样做,你可以编写自己的add函数,并将新Object的类与集合中第一个Object的类进行比较。 (如果您的收藏中没有对象,只需添加它)
void add(Entity ent) {
if (collection == null) {
collection = new Collection<Entity>();
collection.add(ent);
}
else if(ent.getClass().equals(collection.get(0).getClass()) {
collection.add(ent);
}
else {
// wrong class error handling here
}
}
类似的东西。