0

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>();
    }
}

2 Answers 2

3

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>();
}
Sign up to request clarification or add additional context in comments.

7 Comments

I imagine you could do without the Class<T> clazz parameter with this solution, could you not?
Do you even need to provide a Class<T> as a parameter? I always forget exactly how smart the inference is. I would think Foo<A> a = createFoo(); should work.
Or just FooFactory.<A> createFoo()
Very true, clazz isn't needed.
@TomG Or Foo<Integer> iFoo = FooFactory.createFoo(); where the compiler will infer Integer for T.
|
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.