Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a String to generic type

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?

Trying to compile with:

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

results in compile error:

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

like image 636
Pseudos Avatar asked Dec 04 '22 09:12

Pseudos


1 Answers

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
}
like image 90
Andrzej Doyle Avatar answered Dec 15 '22 05:12

Andrzej Doyle