繁体   English   中英

Java自动类型转换的任何字符串

[英]Java automatic Type Casting of any String

有没有一种方法可以将任何String自动转换为Java中的原始数据类型? 例如,具有包含10个字符串的列表:

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

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

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

通过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,...。

没有办法做到这一点。 您可以使用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");
    }

暂无
暂无

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

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