将String转换为泛型类型 [英] Convert a String to generic type

查看:1201
本文介绍了将String转换为泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

尝试编译:

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

导致编译错误:


found:java.lang.String required:
T

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


推荐答案

根据字符串,你需要有一些创建 T 实例的方法(或等效地,将 String 转换为 T )。

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

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

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.

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

In particular, if T happens to be Integer in this case, you'd need to convert the String to an Integer by calling Integer.parseInt(element). However, the part of the code that you've copied doesn't know what T is 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:

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
}

这篇关于将String转换为泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆