开发者

Convert a String to generic type

开发者 https://www.devze.com 2023-02-21 17:33 出处:网络
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

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 th开发者_JAVA百科at 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?

Trying to compile with:

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

results in compile error:

"found : java.lang.String required: 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 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.

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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号