【发布时间】:2014-02-13 18:57:56
【问题描述】:
我有一个 Java 类:
public class Parent
{
public int parentVal;
}
这将有几个继承的 Groovy 类,例如:
class Child1 extends Parent
{
def value1;
}
class Child2 extends Parent
{
def value2;
}
我希望在 Groovy 中有一个集合,该集合被限制为仅包含 Child1 或 Child2 实例,因此如果集合包含 Child1 实例,则它不能包含 Child2 实例(或其他任何实例)。这是我的尝试:
import java.util.ArrayList;
public class MyCollection<T extends Parent>
{
private ArrayList<T> list = new ArrayList<T>();
public void setType(Class<T> cls)
{
this.cls = cls;
}
public void add(T item) throws Exception
{
if(item.getClass() == cls)
{
list.add(item);
}
else
{
throw new Exception("wrong argument type");
}
}
public T getItem(int index)
{
return list.get(index);
}
private Class<T> cls;
}
在我的 Groovy 脚本中:
def c1 = new Child1()
c1.value1 = 1
c1.parentVal = 2;
def c2 = new Child2()
c2.value2 = 2
c2.parentVal = 3;
def myCol = new MyCollection()
myCol.setType(Child1.class)
myCol.add(c1)
myCol.add(c2) // throws an exception
最后一条语句确实引发了“错误的参数类型”异常,但我是 Java 和 Groovy 的新手,所以我可能做错了整个事情。非常感谢任何建议。
【问题讨论】: