Is it possible to create variables at runtime in Java?

后端 未结 6 1505
无人共我
无人共我 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 15:47

    Is it possible to create variables at runtime in Java?

    The simple answer is No.

    Java is a static language and does not support the injection of new variable declarations into an existing compiled program. There are alternatives (in order of decreasing usefulness / increasing difficulty):

    • Represent your "variables" as name / value pairs in a Map. Or come up with some other design that doesn't require real dynamic variables.
    • Use a scripting language that runs on the JVM and is callable from Java.
    • Use some kind of templating mechanism to generate new source code containing the declarations, and compile and load it dynamically.
    • Use a byte code manipulation library (e.g. BCEL) to create class files on the fly and then dynamically load them.

    The first approach is the best. Java is a static language, and works best if you don't fight it. If this is a problem for you, maybe you are using the wrong language.

    The last two are difficult / complicated and have significant performance costs. They are almost certainly not going to help ...

    0 讨论(0)
  • 2020-11-28 15:49

    The question is not why you want to do it but 'what are you going to do with it?'. So suppose at runtime variable with the name fruits2 magically appeared on the stack of your method. Now what? You had to know its name at compile time to take advantage of it. Reflection will not help you access local variables.

    Anyway, I would be interested if you described more detailed use case.

    0 讨论(0)
  • 2020-11-28 15:54

    Can you perhaps elaborate, not sure what you're doing different here. Of course you can create three different strings. However i believe the syntax in java is string xx = new string("DDFD");

    Edit:

    By this i mean, what are you trying to change here. You can allocate memory dynamically therefore you can create "variables" dynamically. HOWEVER you cannot create a "variable" in the primitive fashion such as "int x = 0;" in run time, however you can add nodes to linked lists, resize arrays, etc during run time.

    0 讨论(0)
  • 2020-11-28 15:55

    You're not going to be able to modify a class that's already been loaded into the JVM. However, you could conceivably use ASM < http://asm.ow2.org/ > or BCEL < http://commons.apache.org/bcel/> to dynamically generate a new class that has the dynamically-defined fields.

    Way more trouble than it's worth. Seriously, just use a HashMap!

    0 讨论(0)
  • 2020-11-28 15:57

    The way you phrased your question, people won't understand what you're asking. I believe (if I DO understand) the answer to your question (which should be phrased: "is it possible to dynamically create variables at run time") is "not as you've presented it".

    You're right, there's no analog to javascript's (very powerful, but slow and fraught with hazards "eval" function, in Java), and that is precisely what you would need to get this to do what you're hoping to do.

    The closest that exists is a hashmap (which is actually pretty close) where you can designate the key at run time, and then set the value. It's fairly versatile as you can have an map that will allow for whatever type you want stored in the field.

    0 讨论(0)
  • 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();
        }
    
    }
    

    }

    0 讨论(0)
提交回复
热议问题