我正在尝试编写一个通用方法来从字符串中解析对象。明确地说,我有以下不太优雅的实现:
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 ...
}
有没有更好的方法来实现这个?
最佳答案
您的方法可以只有一行代码:
public static <T> T parseObjectFromString(String s, Class<T> clazz) throws Exception {
return clazz.getConstructor(new Class[] {String.class }).newInstance(s);
}
用不同的类进行测试:
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());
输出:
Obj: 123; type: Integer
Obj: str; type: String
Obj: 123; type: BigDecimal
Obj: java.text.SimpleDateFormat@38d640; type: SimpleDateFormat
关于java - 在 Java 中从字符串解析对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2018570/