java java泛型字符串到<T>解析器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9950800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java generic String to <T> parser
提问by cqcallaw
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.
是否有一种直接的方法来实现具有以下签名的方法?至少,实现需要处理原始类型(例如 Double 和 Integer)。非原始类型将是一个不错的奖励。
//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.
对于实现 FromString 接口(或等效接口)的对象,实现将是微不足道的,但我还没有找到任何这样的东西。我也没有找到使用反射的功能实现。
采纳答案by BalusC
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.
这只有在您提供Class<T>
另一个参数时才有可能。在T
本身不包含有关所需的返回类型的任何信息。
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.
然后你可以通过type
. 在这篇博客文章中可以找到一个具体的例子。
回答by Tom Hawtin - tackline
You want an object that parses a particular type in a particular way. Obviously it's not possible to determine how to parse an arbitrary type just from the type. Also, you probably want some control over how the parsing is done. Are commas in numbers okay, for example. Should whitespace be trimmed?
您需要一个以特定方式解析特定类型的对象。显然,仅凭类型无法确定如何解析任意类型。此外,您可能希望对解析的完成方式进行一些控制。例如,数字中的逗号可以吗?应该修剪空白吗?
interface Parser<T> {
T fromString(String str, T dftl);
}
Single Abstract Method types should hopefully be less verbose to implement in Java SE 8.
希望在 Java SE 8 中实现单个抽象方法类型应该不那么冗长。
回答by etxalpo
Perhaps not answering the question how to implement the solution, but there is a library that does just this (i.e has almost an identical API as requested). It's called type-parserand could be used something like this:
也许没有回答如何实现解决方案的问题,但是有一个库可以做到这一点(即具有几乎与请求相同的 API)。它被称为类型解析器,可以像这样使用:
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);