简体   繁体   English

java generic String to <T> 解析器

[英]java generic String to <T> parser

Is there a straight-forward way to implement a method with the following signature? 是否有直接的方法来实现具有以下签名的方法? At minimum, the implementation would need to handle primitive types (eg Double and Integer). 至少,实现需要处理原始类型(例如Double和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. 对于实现FromString接口(或等效的)的对象,实现将是微不足道的,但我还没有找到任何这样的东西。 I also haven't found a functional implementation that uses reflection. 我还没有找到使用反射的功能实现。

That's only possible if you provide Class<T> as another argument. 只有将Class<T>作为另一个参数提供时才有可能。 The T itself does not contain any information about the desired return type. T本身不包含有关所需返回类型的任何信息。

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

Then you can figure the type by type . 然后您可以按type A concrete example can be found in this blog article . 这篇博客文章中可以找到一个具体的例子。

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中,单个抽象方法类型应该不那么冗长。

Perhaps not answering the question how to implement the solution, but there is a library that does just this (ie has almost an identical API as requested). 也许没有回答如何实现解决方案的问题,但是有一个库可以做到这一点(即具有与请求几乎相同的API)。 It's called type-parser and could 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM