This is a follow-up to my question:
Create instance of generic type in Java when parameterized type passes through hierarchies?
For attempting to create a new generic from a contained class, I tried to adapt Steve B's approach of creating an anonymous subclass:
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public class ParameterizedTypeEg {
ParameterizedTypeEg () {
ContainsParameterized<String> containString = new ContainsParameterized<String>();
}
public class Parameterized<E> {
Parameterized () {
}
public Class<E> getTypeParameterClass() {
Type type = getClass().getGenericSuperclass();
ParameterizedType paramType = (ParameterizedType) type;
return (Class<E>) paramType.getActualTypeArguments()[0];
}
public Constructor<E> getTypeParameterConstructor() {
Constructor<E> constructor = null;
try {
constructor = getTypeParameterClass().getConstructor(QueriedColor.class);
} catch (NoSuchMethodException e) { System.err.println(e); }
return constructor;
}
}
class ContainsParameterized<E> {
ContainsParameterized () {
Parameterized<E> contained = new Parameterized<E>(){};
try {
E element = contained.getTypeParameterConstructor().newInstance();
}
catch (InstantiationException e) { System.err.println(e); }
catch (IllegalAccessException e) { System.err.println(e); }
catch (InvocationTargetException e) { System.err.println(e); }
}
}
public static void main(String[] args) {
new ParameterizedTypeEg();
}
}
Please note the line Parameterized contained = new Parameterized(){};
Here I am attempting to create the anonymous subclass, as suggested by Steve B in the other post. However, I get a ClassCastException in the getTypeParameterClass() method. This is the same type of exception as in my other posting. That lead me to think that I could use the same solution as Steve B suggested for that problem.