I'm trying to work with generics mostly for practice and for a little idea I had.
At the moment I have a problem with: ClassCastException:java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType.
Most of the topics I found about this where from users that posted very specific code. This makes it really harder for me to understand. I tried to make the problem as simple as possible but still related to my actual problem. I hope someone can help.
The Bar class:
class Bar { }
The Foo class:
class Foo<T> {
ArrayList<Object> list;
Foo(int initialCapacity) {
init(initialCapacity);
}
void init(int initialCapacity) {
list = new ArrayList<Object>(initialCapacity);
for (int i = 0; i < initialCapacity; i++) {
try {
list.add(((Class)((ParameterizedType)this.getClass().
getGenericSuperclass()).getActualTypeArguments()[0]).newInstance());
}
catch (InstantiationException e) {
}
catch (IllegalAccessException e) {
}
}
}
}
use:
Foo<Bar> com = new Foo<Bar>(100);
list.add(((Class)((ParameterizedType)this.getClass(). getGenericSuperclass()).getActualTypeArguments()[0]).newInstance());