Convert string to generic type

My program should receive input from a file, input can be characters, integers or characters. With this, I have to create a tree from the elements specified in the file. The input type is set at the beginning of the file. My problem is that my insertNode function returns the element as a generic type T, but the file is read as strings. How to convert String to type T?

Trying to compile with:

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

leads to a compilation error:

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

+4
source share
1 answer

You need to have a way to instantiate T based on String (or, equivalently, convert String to T ).

Casting does not do what you might think it does in this case. All throws say about the type system: "I know that you have a different, less specific idea about which class this object is, but I tell you that this is Foo . Go ahead, check its class runtime and make sure I'm right ! " In this case, however, the string is not necessarily T , so the cast fails. Casting is not converted, it just eliminates the inconsistencies .

In particular, if in this case T turns out to be Integer , you need to convert String to Integer by calling Integer.parseInt(element) . However, part of the code that you copied does not know what will be T when it is called and will not be able to perform these conversions on its own. Therefore, you will need to pass some parameterized 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 } 
+15
source

Source: https://habr.com/ru/post/1346026/


All Articles