简体   繁体   中英

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?

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 ...)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM