I have an Object
that sometimes contains a List<Object>
. I want to check it with instanceof
, and if it is, then add some elements to it.
void add(Object toAdd) {
Object obj = getValue();
if (obj instanceof List<?>) {
List<?> list = obj;
if (list instanceof List<Object>) { // Error
((List<Object>) list).add(toAdd);
} else {
List<Object> newList = new ArrayList<Object>(list);
newList.add(toAdd);
setValue(newList);
}
return;
}
throw new SomeException();
}
And it says I can't check if it is instanceof List<Object>
because java doesn't care and erased the type in <>
.
Does this mean I have to create new ArrayList every time? Or is there a way to check that, eg. with reflection?