javareflectionbeanshelljanino

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.

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.


Solution

  • 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]