简体   繁体   English

如何在运行时从字符串表示形式创建Java对象

[英]How to create a Java object from a string representation at runtime

Eg if I have a string "{1,2,3,4,5}" I would like to get an int[] object from that string. 例如,如果我有一个字符串"{1,2,3,4,5}"我想从该字符串中获取一个int []对象。

I have looked a bit at Janino and Beanshell, but can't seem to find the correct way to get them to do this for me. 我对Janino和Beanshell有所了解,但似乎找不到正确的方法来使他们为我做这件事。

I am looking for a generic solution, one that works for all types - not only integer arrays. 我正在寻找一种通用解决方案,该解决方案适用于所有类型-不仅限于整数数组。

looks like a parse problem to me. 对我来说似乎是一个解析问题。 look at the string methods :) 看一下字符串方法:)

the code could look like: 代码如下所示:

String s = "{1,2,3,4,5}"
String justIntegers = s.substring(1, s.length()-1);
LinkedList<Integer> l = new LinkedList();
for (String string: justIntegers.split(','))
l.add(Integer.valuesOf(string));
l.toArray();

if you are using strings to send/save objects pls use xml or json... 如果您使用字符串发送/保存对象,请使用xml或json ...

Take a look at https://stackoverflow.com/a/2605050/1458047 看看https://stackoverflow.com/a/2605050/1458047

The answer proposes a few options. 答案提出了一些选择。

Better to use Regular Expression .Not necessary that your String is Array it could be any String which contains numbers. 最好使用Regular Expression 。您的String不必是Array它可以是任何包含数字的String

        String s="{1,2,3,4,5}";
        Pattern p = Pattern.compile("-?\\d+");
        Matcher m = p.matcher(s);
        List<Integer> list=new ArrayList<Integer>();
        while (m.find()) {
          Integer num=new Integer(m.group());

          list.add(num);
        }

        System.out.println(list);

Output: 输出:

[1, 2, 3, 4, 5]

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

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