java通用字符串转换为< T>解析器 [英] java generic String to <T> parser

查看:760
本文介绍了java通用字符串转换为< T>解析器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一个直接的方法来实现一个具有以下签名的方法?至少,实现需要处理基本类型(例如Double和Integer)。非原始类型将是一个很好的奖励。

  //尝试从给定的输入字符串实例化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通用字符串转换为&lt; T&gt;解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆