单个方法返回一个类的不同泛型类型的实例(Single method to return an instance of different generic type of a class)

编程入门 行业动态 更新时间:2024-10-25 00:25:08
单个方法返回一个类的不同泛型类型的实例(Single method to return an instance of different generic type of a class)

我有一个泛型类如下:

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

更多推荐

本文发布于:2023-07-31 00:19:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1340562.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实例   类型   方法   Single   method

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!