Java自动类型转换任何String

时间:2014-07-22 13:24:54

标签: java casting type-conversion

有没有办法将任何String自动转换为Java中的原始数据类型?例如,拥有包含10个字符串的List:

string1 = "1234"
string2 = "12.34"
string3 = "String"
string4 = "0.53"
...

我想将它们全部放在一个方法中,然后将值转换为正确的数据类型(Float,Integer,String):

int1 = 1234
float1 = 12.34
string1 = "String"
float2 = 0.53
...

2 个答案:

答案 0 :(得分:0)

只需通过 RegEx

实现
String string = "/**Place your value*/";
if (string.matches("\\d+")) {
 int i = Integer.parseInt(string); 
} else if (string.matches("^([+-]?\\d*\\.?\\d*)$)")) {
 float f = Float.parseFloat(string); 
}

以同样的方式你可以解析double,long,....

答案 1 :(得分:-1)

没有办法做到这一点。您可以使用instanceof

测试其类的对象
Object integerValue = 1234;
    Object doubleValue = 12.34;
    Object array = new String[] { "This", "is", "a", "Stringarray" };
    if (integerValue instanceof Integer) {
        System.out.println("it's an Integer! Classname: " + integerValue.getClass().getName()); // will be printed
    }
    if (doubleValue instanceof Double) {
        System.out.println("this one is a Double *___* Classname: " + doubleValue.getClass().getName()); // will be printed
    }
    if (array instanceof String) {
        System.out.println("Is it a String?");
    } else if (array instanceof String[]) {
        System.out.println("It's a Stringarray :O! Classname: " + array.getClass().getName()); // will be printed
    } else {
        System.out.println("Huh? Something went wrong here :D");
    }