我需要的是定义一个可以键入以保存特定类型对象的类。保持的对象还需要有一个返回包含类的引用。
我不确定我是否正在咆哮错误的树,或者我是否接近解决方案,而不是关于类型安全的Eclipse警告。
界面看起来像(这似乎是正确定义的):
public interface ItemInterface {
public ItemOwner<? extends ItemInterface> getOwner();
public void setOwner(ItemOwner<? extends ItemInterface> owner);
}
所有者类看起来像(这似乎也很简单):
public class ItemOwner <T extends ItemInterface> {
private NavigableSet<T> items = new TreeSet<T>();
public Set<T> getItems() {
return Collections.unmodifiableSet(items);
}
public void addItem(T item) {
// if we are passed a null, throw an ILA error
if (item == null)
throw new IllegalArgumentException("Argument was null.");
// check whether already is a member
if (items.contains(item))
throw new IllegalArgumentException("Already a member.");
items.add(item);
item.setOwner(this);
}
public void removeNode(T item) {
// if we are passed a null, throw an ILA error
if (item == null)
throw new IllegalArgumentException("Argument was null.");
// check whether node already is a member
if (!items.contains(item))
throw new IllegalArgumentException("Not a member.");
items.remove(item);
}
}
可以拥有的物品如下:
public class Item implements ItemInterface {
private ItemOwner<? extends ItemInterface> owner;
public ItemOwner<? extends ItemInterface> getOwner() {
return owner;
}
public void setOwner(ItemOwner<? extends ItemInterface> owner) {
// if we are passed a null, throw an ILA error
if (owner== null)
throw new IllegalArgumentException("Argument was null.");
this.owner = owner;
}
}
我在Eclipse中遇到的错误是对getOwner()的警告:“ItemOwnerneeds类型的表达式未经检查转换为符合ItemOwner”。