Is it possible to create variables at runtime in Java?

后端 未结 6 1568
无人共我
无人共我 2020-11-28 15:22

For example, say I wanted to \"extract\" String[] fruits = {\"Pear\", \"Banana\", \"Apple\"}; into three separate variables, eg:

for (int i=0; i         


        
6条回答
  •  孤城傲影
    2020-11-28 16:05

    Would Janino be useful for you?

    Here's some code. I think it's close to what you want, but I'm not sure.

    package misc;
    
    import java.lang.reflect.InvocationTargetException;
    
    import org.codehaus.janino.CompileException;
    import org.codehaus.janino.ScriptEvaluator;
    import org.codehaus.janino.Parser.ParseException;
    import org.codehaus.janino.Scanner.ScanException;
    
    public class JaninoExample {
    public static void main(String[] args) {
        String in = " {\"Pear\", \"Banana\", \"Apple\"};";
        try {
            ScriptEvaluator se = new ScriptEvaluator("return new String[]"+in,String[].class);
            try {
                String[] fruits = (String[])se.evaluate(new Object[]{});
                for(String fruit:fruits){
                    System.out.println(fruit);
                }
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        } catch (CompileException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (ScanException e) {
            e.printStackTrace();
        }
    
    }
    

    }

提交回复
热议问题