Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is there a straight-forward way to implement a method with the following signature? At minimum, the implementation would need to 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)

Implementation would be trivial for objects that implemented a FromString interface (or equivalent), but I haven't found any such thing. I also haven't found a functional implementation that uses reflection.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
307 views
Welcome To Ask or Share your Answers For Others

1 Answer

That's only possible if you provide Class<T> as another argument. The T itself does not contain any information about the desired return type.

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

Then you can figure the type by type. A concrete example can be found in this blog article.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...