Java从字符串中解析对象 [英] Parsing Objects from String in Java

查看:58
本文介绍了Java从字符串中解析对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个通用方法来解析字符串中的对象.需要明确的是,我有以下不太优雅的实现:

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?

推荐答案

你的方法可以只有一行代码:

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());

输出:

Obj: 123; type: Integer
Obj: str; type: String
Obj: 123; type: BigDecimal
Obj: java.text.SimpleDateFormat@38d640; type: SimpleDateFormat

这篇关于Java从字符串中解析对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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