How to create a Java object from a string representation at runtime
-
15-06-2021 - |
سؤال
Eg if I have a string "{1,2,3,4,5}"
I would like to get an int[] object from that string.
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.
I am looking for a generic solution, one that works for all types - not only integer arrays.
المحلول
Better to use Regular Expression
.Not necessary that your String
is Array
it could be any String
which contains numbers.
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]
نصائح أخرى
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...
Take a look at https://stackoverflow.com/a/2605050/1458047
The answer proposes a few options.
لا تنتمي إلى StackOverflow