Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a string be converted to an instruction?

This code in Java:

for (Integer x=1; x <= 3; x++) {
    y = "array[" + Integer.toString(x) + "] = a" + Integer.toString(x) + ".getText();";
    System.out.println(y);
    }

prints out:

array[1] = a1.getText();
array[2] = a2.getText();
array[3] = a3.getText();

However, instead of having string y printed out I want it executed. How do I do this in Java?

If this is not possible, is there another way to achieve what I want, different from using the 3 instructions?

array[1] = a1.getText();
array[2] = a2.getText();
array[3] = a3.getText();

For simplicity I have used 3 although I need 20 instructions. More importantly, I am trying to learn more about Java and am looking for a more elegant solution.

like image 356
Jan Nordgreen Avatar asked Dec 18 '25 18:12

Jan Nordgreen


1 Answers

What you're looking for is "eval" in many interpreted languages. Java does not allow you to eval source code at run time. This is a property of being a compiled rather than interpreted language.

You can get some of the functionality through reflection or bytecode generation, but these are advanced features usually used by people developing frameworks or libraries, not a routine part of everyday programming.

like image 112
Kevin Peterson Avatar answered Dec 20 '25 06:12

Kevin Peterson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!