我有一个泛型类如下:
MyClass<T> { .... }现在,我想要创建一个通用方法,例如public MyClass<T> getMyClassInstance(Type t){...} ,其中我传递一个类型,这个方法给出了一个具有该类型的MyClass实例。
请参阅以下示例。
如果我按如下方式调用此方法, getMyClassInstance(Integer_type) ,则返回MyClass<Integer>实例。
类似地,如果我按如下方式调用此方法, getMyClassInstance(String_type) ,则返回MyClass<String>实例。
我该怎么写这个方法? 如果无法做到,有没有其他更好的方式来做这样的事情?
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.
If I call this method as follows, getMyClassInstance(Integer_type), then it returns the MyClass<Integer> instance.
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?
最满意答案
对于此的简单应用程序,您甚至不需要传入Type或Class参数。 考虑以下:
public <T> List<T> getList() { return new ArrayList<>(); }使用它很简单:
List<Integer> lst = getList();编译器将推断所需列表的类型。
请注意,传入Type参数可以获得更大的灵活性,尤其是在您可能事先不知道要返回哪种List情况下。 但是这种语法,恕我直言,更自然地阅读, 可能适合你想做的事情。 (我说“可能”,因为你没有提供大量细节...)
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 ...)
更多推荐
发布评论