Java从字符串中解析对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2018570/
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
Parsing Objects from String in Java
提问by Delip
I am trying to write a general method to parse objects from strings. To be clear, I have the following not-so-elegant implementation:
我正在尝试编写一个通用方法来解析字符串中的对象。需要明确的是,我有以下不太优雅的实现:
public static Object parseObjectFromString(String s, Class class) throws Exception {
String className = class.getSimpleName();
if(className.equals("Integer")) {
return Integer.parseInt(s);
}
else if(className.equals("Float")) {
return Float.parseFloat(s);
}
else if ...
}
Is there a better way to implement this?
有没有更好的方法来实现这一点?
采纳答案by True Soft
Your method can have a single line of code:
您的方法可以有一行代码:
public static <T> T parseObjectFromString(String s, Class<T> clazz) throws Exception {
return clazz.getConstructor(new Class[] {String.class }).newInstance(s);
}
Testing with different classes:
使用不同的类进行测试:
Object obj1 = parseObjectFromString("123", Integer.class);
System.out.println("Obj: " + obj1.toString() + "; type: " + obj1.getClass().getSimpleName());
BigDecimal obj2 = parseObjectFromString("123", BigDecimal.class);
System.out.println("Obj: " + obj2.toString() + "; type: " + obj2.getClass().getSimpleName());
Object obj3 = parseObjectFromString("str", String.class);
System.out.println("Obj: " + obj3.toString() + "; type: " + obj3.getClass().getSimpleName());
Object obj4 = parseObjectFromString("yyyy", SimpleDateFormat.class);
System.out.println("Obj: " + obj4.toString() + "; type: " + obj4.getClass().getSimpleName());
The output:
输出:
Obj: 123; type: Integer
Obj: str; type: String
Obj: 123; type: BigDecimal
Obj: java.text.SimpleDateFormat@38d640; type: SimpleDateFormat
回答by Chip Uni
I'm not sure what you're trying to do. Here's a few different guesses:
我不确定你想做什么。这里有几个不同的猜测:
- You want to be able to convert an object to a string, and vice-versa.
- 您希望能够将对象转换为字符串,反之亦然。
You should look into serialization. I use XStream, but writeObjectand java.beans.XMLEncoderalso works.
您应该研究序列化。我使用XStream,但writeObject和java.beans.XMLEncoder也有效。
- The user enters text, and you want to coerce it to the "right" type, of which there are many.
- 用户输入文本,您想将其强制为“正确”类型,其中有很多。
Usually, this means a problem with the user specification. What are you receiving from the user, and why would it be able to be so many different kinds?
通常,这意味着用户规范存在问题。你从用户那里得到了什么,为什么会有这么多不同的种类?
In general, you will want the type to be as broad as possible: use double
if it's a number, and String
for almost everything else. Then build other things from that variable. But don't pass in the type: usually, the type should be very obvious.
通常,您会希望类型尽可能广泛:double
如果它是数字,则使用,并且String
几乎用于其他所有内容。然后从该变量构建其他东西。但是不要传入类型:通常,类型应该很明显。
回答by Bozho
NumberUtils.createNumber(str)
(from apache commons-lang)
NumberUtils.createNumber(str)
(来自 apache commons-lang)
It decides what type of number to create, so you don't pass the class.
它决定要创建的数字类型,因此您无需通过课程。
回答by Itay Maman
How about enums?
枚举呢?
public enum Types {
INTEGER {
@Override
public Object parse(String s) { return Integer.parseInt(s); }
},
FLOAT {
@Override
public Object parse(String s) { return Float.parseFloat(s); }
}
...
;
public abstract Object parse(String s);
public static Object parseObjectFromString(String s, Class<?> cls) {
return valueOf(cls.getSimpleName().toUpperCase()).parse(s);
}
}
public static void main(String[] args) {
System.out.println(Types.parseObjectFromString("5", Integer.class));
}
回答by PSpeed
If those are your only types of examples, then you can also do something like:
如果这些是您唯一的示例类型,那么您还可以执行以下操作:
Constructor ctor = Class.getConstructor( String.class );
return ctor.newInstance( s );
More information may provide for better answers. I'd be very much surprised if there isn't already some utility code out there that meets your specifications. There are a few ways to tackle this problem depending on the actual requirements.
更多信息可能会提供更好的答案。如果还没有一些实用程序代码符合您的规范,我会感到非常惊讶。根据实际需求,有几种方法可以解决这个问题。
回答by cchabanois
To convert from an Object (here a String) to another one, you can use transmorph:
要将对象(此处为字符串)转换为另一个对象,您可以使用transmorph:
Transmorph transmorph = new Transmorph(new DefaultConverters());
float myFloat = transmorph.convert("55.2",Float.TYPE);
long[] longsArray = transmorph.convert(new Integer[] { 1, 2, 3, 4 }, long[].class);