Skip to content
Advertisement

Is it possible to create variables at runtime in Java?

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

for (int i=0; i != fruits.length; ++i) {
    // of course there's 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 that, ignoring the “Why the heck would you want to do that?” question that you might be urged to ask me.

Similar questions have been asked many times before, but the real answer was never given, because what the OP really needed was to use a different approach. That’s fine, but is this possible at all?

I have looked at reflection and it doesn’t seem like there are any methods that would allow me even to add extra fields to an instance, let alone dynamically create locals.

Advertisement

Answer

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 …

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement