Search code examples
javagenericstostringvalue-of

Java valueOf method for generic class


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?
    }
}

Solution

  • You can't do this with generics. Generics are just casts the compiler puts in for you, statically. So, if you couldn't do this with casts you write in the code (that is, you can't have a different cast for different strings), you can't do it with generics either.

    You need some sort of key instead of a String which conveys the type T/E. You can pass in the Class<E> directly:

        public static <E> Foo<E> valueOf(Class<E> clazz) throws ClassNotFoundException {
            // ...
        }