Is it possible to create variables at runtime in Java?

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

 for (int i=0; i != fruits.length; ++i) { // of course there no eval in Java eval("String fruit + i = " + fruits[i] + ";"); } // ie: code that creates something equivalent to the following declarations: String fruit0 = "Pear"; String fruit1 = "Banana"; String fruit2 = "Apple"; 

How could I do this, ignoring "Why the hell do you want to do this?" the question is that you may be asked to ask me.

Similar questions were asked many times before, but the real answer was never given, because the OP really needs to use a different approach. This is great, but is it even possible?

I looked at the reflection, and it does not seem that there are any methods that would even allow me to add additional instances to the instance, not to mention the dynamic creation of locales.

+4
source share
6 answers

Is it possible to create variables at run time 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 utility / increasing complexity):

  • Think of your “variables” as name / value pairs in a Map . Or come up with a different design that does not require real dynamic variables.
  • Use a scripting language that runs on the JVM and can be invoked with Java.
  • Use some kind of template engine to generate new source code containing declarations, and compile and load it dynamically.
  • Use a byte code management library (such as 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, you may be using the wrong language.

The last two are complex / complex and have significant operating costs. They almost certainly will not help ...

+10
source

The question is not why you want to do this, but "what are you going to do with it?" Suppose that at run time, a variable named fruits2 magically fruits2 stack of your method. Now what? You had to find out his name at compile time to use it. Reflection does not help you access local variables.

In any case, I would be interested if you could describe a more detailed use case.

+4
source

As you formulated your question, people will not understand what you are asking. I consider (if I understand it) the answer to your question (which should be worded: "is it possible to dynamically create variables at runtime") "not the way you presented it."

You are right, there is no analogue of javascript (very powerful, but slow and fraught with the danger of “eval” in Java), and this is what you need to make it do what you hope to do.

The closest that exists is a hashmap (which is actually pretty close) where you can assign a key at runtime and then set the value. It is quite universal, since you can have a card that allows you to use any type that you want to keep in the field.

+1
source

You cannot change a class that has already been loaded into the JVM. However, you could use ASM < http://asm.ow2.org/ > or BCEL < http://commons.apache.org/bcel/ > to dynamically create a new class with dynamically defined fields.

Way more trouble than it costs. Seriously, just use the HashMap!

0
source

Could Yanino be useful to you?

Here is the code. I think this is 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
source

Can you please clarify, do not know what you are doing here. Of course, you can create three different lines. However, I believe that the syntax in java is line xx = new line ("DDFD");

Edit:

By this I mean that you are trying to change here. You can dynamically allocate memory, so you can dynamically create "variables". HOWEVER, you cannot create a "variable" in a primitive style such as "int x = 0;" at run time, however, you can add nodes to linked lists, resize arrays, etc. at runtime.

-1
source

All Articles