简体   繁体   English

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

[英]Java automatic Type Casting of any String

is there a way to cast any String automatically to its primitive data type in Java? 有没有一种方法可以将任何String自动转换为Java中的原始数据类型? For example having a List with 10 Strings: 例如,具有包含10个字符串的列表:

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

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

Simply achieve by RegEx 通过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, .... 以同样的方式,您可以解析double,long,...。

There is no way to do that. 没有办法做到这一点。 you can test an object for its class by using instanceof 您可以使用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