-1

In Python it's quite easy:

def function(variable_name,variable_value):
    exec(str(variable_name) + "=" + str(variable_value))

exec() converts string into code to run; in this case it creates a variable. I'm looking for something like this in Java:

static void method (String variable_name; String variable_value){
     exec_eval_in_java("String " + variable_name + " = " + variable_value + ";");
}
khelwood
  • 55,782
  • 14
  • 81
  • 108
Matteo
  • 19
  • 5

1 Answers1

1

You can do it Dynamically if you compile and load a java class:

String className = "package.myClass";
String code = "package package;\n" + 
    "public class myClass{}\n"

and so on you can write your code like that and then:

Class class = CompilerUtils.CACHED_COMPILER.loadFromJava(className, code);
Runnable runnable= (Runnable) class.newInstance();
runnable.run();

You can have a look into: How do you dynamically compile and load external java classes? and Is there an equivalent to Python's exec() function in Java?

You can also check the git hub Java-Runtime-Compiler

Mario Khoury
  • 372
  • 1
  • 7