t1ms0n t1ms0n - 1 year ago 84
Java Question

Executing String with java statement

I was wondering how can I execute String variable with some java expression, lets say I have created 10 cars object in test class c1-c10 without using array eg.

for(int i = 1; int < 11; i++)
String getCarBrand = "car" + i + ".getBrand();"
System.out.println("Car number " + i + "is "+ getCarBrand);

I know that I could do it easily with arrays but I want to know if there's a way of executing String as a java expression.


Answer Source

You can't.

  1. You can't conveniently evaluate Java code just from a string. You might have to compile the string into an independent class, and then load it, but it will totally not be what you are looking for.
  2. Java variable names only exist at source. Even in compile .class files there are no longer variable names. <--- This is particularly important, because for most other things it is still possible to do with reflections, such as class fields. See Appendix I.
  3. Learn using arrays to iterate a collection of Java objects.

Appendix I

public class Foo {
    public Car car1;
    public Car car2;
    public Car car3;
    public Car car4;
    public Car car5;

    public String toString() {
        StringBuilder builder = new StringBuilder();
        for(int i = 1; i <= 5; i++) {
            builder.append(Foo.class.getField("car" + i).get(this).toString());
        return builder.toString();


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download