같은 클래스의 지 확인 Groovy는 Child1 또는 Child2 인스턴스 만 포함하도록 제한되므로 컬렉션에 Child1 인스턴스가 포함되어 있으면 Child2 인스턴스 (또는 다른 것)를 포함 할 수 없습니다. 이것이 내 시도 :그루비의 ArrayList 객체 내가 자바 클래스가
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;
}
내 그루비 스크립트 :
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
는 마지막 문장은 정말 "잘못된 인수 유형"예외가 발생합니다,하지만 난 내가 자바와 그루비에 새로운 해요 아마 모든 일을 잘못하고있는 것 같아. 어떤 조언을 크게 주시면 감사하겠습니다.
당신에게 감사를 모두 시도 –