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);
source share