0

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.

Thanks.

tym
  • 73
  • 1
  • 6
  • 3
    Not my downvote, but I have no idea what you want to do. If you want your car class to have a string representation, then just override `toString()`. – Tim Biegeleisen Nov 05 '16 at 14:47
  • @TimBiegeleisen Essentially, they want to use the equivalent of `eval` to execute code in the string. This isn't possible. – Andrew Li Nov 05 '16 at 14:48
  • 4
    Java is a compiled, statically typed language. There isn't a Java `eval`. – Elliott Frisch Nov 05 '16 at 14:48
  • I think in Java it is impossible to execute strings as code, because Java is strongly typed. This could be achieved by using some functional languages. – Mr.D Nov 05 '16 at 14:49
  • @AndrewLi He could build a rudimentary parser and do this, or just use `toString()` as it was intended. – Tim Biegeleisen Nov 05 '16 at 14:53
  • @Mr.D I don't think "strong typing" has direct and absolute relationship with evaluating code. If a language has a compiler that stores the state of the source code at a point, it is still possible to call the evaluated code like a function with the local variables copied. – SOFe Nov 05 '16 at 14:54
  • @Mr.D, I guess so, I know it's pretty easy to do with python – tym Nov 05 '16 at 14:55

1 Answers1

7

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();
    }
}
Graham
  • 7,431
  • 18
  • 59
  • 84
SOFe
  • 7,867
  • 4
  • 33
  • 61
  • That answer my question, I know how to do it with array or how to use toString() but just wanted to know if it's possible. Thanks! – tym Nov 05 '16 at 14:53