java 将字符串转换为泛型类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5498776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 11:25:02  来源:igfitidea点击:

Convert a String to generic type

javastringgenerics

提问by Pseudos

My program has to recieve input from a file, the input can be chars, integers or characters. With this I have to create a tree out of the elements given in the file. The type of the input is given at the start of the file. My problem is that my insertNode function recieves the element as generic type T, but the file is read as Strings. How can I convert the String to type T?

我的程序必须从文件接收输入,输入可以是字符、整数或字符。有了这个,我必须从文件中给定的元素中创建一棵树。输入的类型在文件的开头给出。我的问题是我的 insertNode 函数将元素作为通用类型 T 接收,但文件被读取为字符串。如何将字符串转换为 T 类型?

Trying to compile with:

尝试编译:

String element = br.readLine();  
T elem = (T)element; 

results in compile error:

导致编译错误:

"found : java.lang.String required: T "

“发现:java.lang.String 需要:T”

回答by Andrzej Doyle

You'd need to have some way of creatingan instance of T, based on a String(or equivalently, converting a Stringto a T).

您需要有某种方式基于 a创建的实例(或等效地,将 a 转换为 a )。TStringStringT

Casting doesn't do what you perhaps think it does in this case. All a cast does is tell the type system, "I know that you have a different, less specific idea of what class this object is, but I'm telling you that it's a Foo. Go ahead, check its run-time class and see that I'm right!". In this case, however, the String is not necessarily a T, which is why the cast fails. Casting doesn't convert, it merely disambiguates.

在这种情况下,铸造不会做你可能认为它会做的事情。强制转换所做的只是告诉类型系统,“我知道你对这个对象是什么类有不同的、不太具体的想法,但我告诉你它是一个Foo. 继续,检查它的运行时类,看看我是对的!”。但是,在这种情况下, String 不一定是 a T,这就是强制转换失败的原因。 铸造不会转换,它只是消除歧义

In particular, if Thappens to be Integerin this case, you'd need to convertthe String to an Integer by calling Integer.parseInt(element). However, the part of the code that you've copied doesn't know what Tis going to be when it's invoked, and can't perform these conversions itself. Hence you'd need to pass in some parameterised helper object to perform the conversion for you, something like the following:

特别是,如果T碰巧Integer在这种情况下,您需要通过调用字符串转换为整数Integer.parseInt(element)。但是,您复制的那部分代码不知道T调用时会发生什么,并且无法自行执行这些转换。因此,您需要传入一些参数化的辅助对象来为您执行转换,如下所示:

interface Transformer<I, O> {
    O transform(I input);
}

...

public void yourMethod(BufferedReader br, Transformer<String, T> transformer) {

    String element = br.readLine();
    T elem = transformer.transform(element);

    // Do what you want with your new T
}