简体   繁体   中英

Java automatic Type Casting of any String

is there a way to cast any String automatically to its primitive data type in Java? For example having a List with 10 Strings:

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

I would like to hand them all in a method and get the value back converted in its correct data type (Float, Integer, String):

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

Simply achieve by 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); 
}

In the same manner you can parse double, long, ....

There is no way to do that. you can test an object for its class by using 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");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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