Java generic String for <T> parser

Is there a direct way to implement a method with the following signature? At a minimum, an implementation should handle primitive types (e.g. Double and Integer). Non-primitive types would be a nice bonus.

//Attempt to instantiate an object of type T from the given input string //Return a default value if parsing fails static <T> T fromString(String input, T defaultValue) 

The implementation would be trivial for objects that implemented the FromString interface (or equivalent), but I did not find such a thing. I also did not find a functional implementation that uses reflection.

+8
java generics string-parsing
source share
3 answers

This is only possible if you have provided Class<T> as another argument. T itself does not contain information about the desired type of return.

 static <T> T fromString(String input, Class<T> type, T defaultValue) 

Then you can specify the type type . A specific example can be found in this blog post .

+5
source share

You need an object that processes a certain type in a certain way. Obviously, it is impossible to determine how to parse an arbitrary type from a type only. Also, you probably need some kind of control over how the parsing is performed. For example, commas in numbers. Should spaces be trimmed?

 interface Parser<T> { T fromString(String str, T dftl); } 

Unified abstract method types will hopefully be less verbose for implementation in Java SE 8.

+1
source share

Perhaps without answering the question of how to implement the solution, but there is a library that does just that (I have an almost identical API on request). It was called type-parser and can be used something like this:

 TypeParser parser = TypeParser.newBuilder().build(); Integer i = parser.parse("1", Integer.class); int i2 = parser.parse("42", int.class); File f = parser.parse("/some/path", File.class); Set<Integer> setOfInts = parser.parse("1,2,3,4", new GenericType<Set<Integer>>() {}); List<Boolean> listOfBooleans = parser.parse("true, false", new GenericType<List<Boolean>>() {}); float[] arrayOfFloat = parser.parse("1.3, .4, 3.56", float[].class); 
0
source share

All Articles