greenPadawan
greenPadawan

Reputation: 1571

Single method to return an instance of different generic type of a class

I have a generic class as follows:

MyClass<T>
{
    ....
}

Now, what I want create a single generic method,say for example public MyClass<T> getMyClassInstance(Type t){...}, in which I pass a type and this method gives an instance of MyClass with that type.


See the following examples.

  1. If I call this method as follows, getMyClassInstance(Integer_type), then it returns the MyClass<Integer> instance.

  2. Similarly, if I call this method as follows, getMyClassInstance(String_type), then it returns the MyClass<String> instance.

How shall I write this method? If it can't be done, is there any alternative way or another better way to do something like this?

Upvotes: 0

Views: 70

Answers (2)

dcsohl
dcsohl

Reputation: 7396

For simple applications of this, you don't even need to pass in a Type or Class argument. Consider the following:

public <T> List<T> getList() {
    return new ArrayList<>();
}

To use this is as simple as:

List<Integer> lst = getList();

The compiler will infer the type of the list desired.

Do note that you will get more flexibility from passing in a Type parameter, especially in cases where you may not know in advance what sort of List you want to get back. But this sort of syntax, IMHO, reads more naturally and may be suited to what you want to do. (I say "may" since you haven't provided a ton of details ...)

Upvotes: 1

Marko Topolnik
Marko Topolnik

Reputation: 200148

The Type class must carry the type parameter on it: Type<T>, so you can declare

<T> MyClass<T> getMyClassInstance(Type<T> t);

If you can't make that happen, then the compiler is blind.

Upvotes: 0

Related Questions