I have my own generic class which goes like this:
C1<T> {
T value;
...
void setValue(T val) {
this.avlue = val;
}
}
Somewhere else i have this collection:
List<C1> list;
Then in a different piece of code I instantiate some objects of type C1 like this:
C1<Integer> a;
C1<Float> b;
C1<String> c;
...
Later i put them in the list;
list.add(a);
list.add(b)
...
The next thing i do is this:
iterate over list doing this:
list.get(i).setValue(obj);
where obj is a variable of type Object which could be an Integer, Float, etc.
Now there problem is that is the instance of C1 returned from the list (lets call it c1) was defined like this:
C1<Type1>
Java will allow this:
c1.setValue(val2);
where val2 is of type Type2 and Type2 is not equal to Type1 and is not even in the same class hierarchy (except Object ofc)!
EDIT:
Forgot to ask the question 🙂
How do i make setValue “Type safe” when accessed the way I’m doing it above?
If you store objects of types
C1<Type1>andC1<Type2>in aList<C1>, it is not possible to determine the exact type when you retrieve an element from the list. You will only know that it is aC1(as all elements in the list).If you really need to ask the
C1at runtime what its type parameter is, you need to store some type token in C1:Then you can call
getTypeParameter()on the instance you got from the list and compare it to the type you expected.Note that this will still allow you to store values of
Type2in aC1<Type1>if you use an unchecked cast. If you want to eliminate this possibility, check the runtime type ofvalagainstclsinsetValue()and throw an exception if they don’t match.