I have a class
A<T> {
T value;
public T getValue() { return value; }
public void setValue(T value) { this.value = value;}
}
And try to use it with non-generic method like this:
A<?>[] as = new A<?>[2]; as[0] = new A<Integer>(); as[1] = new A<String>();
for(A<?> a : as) {
someobj.put(a.getValue()); // <-- got an error "The method put(String) is not applicable for the arguments (capture#2-of ?)"
}
someobj has put(String s), put(Integer i) etc.
How can i do something like dynamic type casting and fix an error?
As explained by Marko, the type of your generic A is lost. But what you could do is to use reflection to invoke the correct “put” method.
Something like this: