Given a generic class Foo<T>
, I would like to create a static method valueOf(String s)
. The String s
should hold the name of a class (e.g. "java.lang.Integer"
). A call to valueOf("java.lang.Integer")
should then return a new object Foo<Integer>
.
In my class (see code below), I want to store the Class<T>
, which is passed as parameter to the constructor Foo(Class<T> clazz)
. But in the valueOf
-method, I am not sure what parameter to pass to the constructor Foo(Class<T> clazz)
of the object I like to return.
Since I am relatively new to java reflections, I am unsure how I can implement this logic to my generic class. I have learned that the Class.forName(String)
method returns an object Class<?>
, but I don't know how to find out the type that the wildcard ? stands for (in case that's possible using reflections), or am I wrong going into this direction?
public class Foo<T> {
private Class<T> clazz;
public Foo(Class<T> clazz) {
this.clazz = clazz;
}
public static <E> Foo<E> valueOf(String s) throws ClassNotFoundException {
Class<?> clazz = Class.forName(s);
// here i am stuck. I would like to return new Foo<E>,
// but what is E, E's class and therefore the parameter for the constructor?
}
}