簡體   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