Hans Z
Hans Z

Reputation: 4744

Java Parameterized Type from Class object

Let's say I have a class called Foo with a generic type.

public class Foo<T> { ...

And I have another, non parameterized class called Foo Factory that generates Foos.

public class FooFactory {
    public static Foo createFoo() { 
        return new Foo();
    }
}

Is there any way to pass a Class clazz parameter into createFoo so that I can create a Foo<clazz>?

public class FooFactory {
    public static Foo createFoo(Class clazz) {
        return new Foo<clazz>();
    }
}

Upvotes: 0

Views: 250

Answers (2)

Sage
Sage

Reputation: 15408

Just make the createFoo function generic:

public static <T> Foo<T> createFoo() {
    return new Foo<>();
}

returns an instance of type Foo<T> and does so for any type T. This is indicated by writing <T> at the beginning of the method signature, which declares T as a new type variable, specifying that createFoo() is a generic method.

Check out : Generic Methods

Upvotes: 0

rgettman
rgettman

Reputation: 178253

Make the createFoo factory method generic:

public static <T> Foo<T> createFoo(Class<T> clazz) {
    return new Foo<T>();
}

Well as it turns out, you don't even need clazz; Java will infer <T> for you, so this will suffice:

public static <T> Foo<T> createFoo() {
    return new Foo<T>();
}

Upvotes: 3

Related Questions