java通用字符串转换为< T>解析器 [英] java generic String to <T> parser
问题描述
//尝试从给定的输入字符串实例化T类型的对象
//解析失败时返回默认值
static< T> T fromString(String input,T defaultValue)
实现对于实现FromString接口的对象来说是微不足道的或相当),但我还没有找到任何这样的事情。我还没有找到使用反射的功能实现。
只有当您提供 Class< T>
作为另一个参数。 T
本身不包含任何有关所需返回类型的信息。
静态< T> T fromString(String input,Class< T> type,T defaultValue)
然后你就可以确定类型由键入
。一个具体的例子可以在这篇博客文章中找到。
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.
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.
这篇关于java通用字符串转换为< T>解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!