variable as function name

edited November 2015 in How To...

Is there a way to use a variable to call a function, or to name another variable?

for example, having two variables called name1;name2 , calling them in a loop as "nameX = 10;" with X as 1 or 2?

The same goes for function name; It is a question I've had for some times, now the problem is surely solved with arrays and objects, but there would be a way(except for calling a function with thread())?

Tagged:

Answers

  • edited November 2015 Answer ✓

    There is no simply way to do what you want.

    This discussion will help with calling a function by its name.

    Using a String to access a variable of the same name can be simulated using HashMap(s)

  • edited November 2015 Answer ✓

    For the variables, you might just be looking for a basic array:

    int[] name = new int[10];
    for(int i = 0; i < 10; i++){
       name[i] = i*10;
    }
    println(name[3]);
    

    For the functions, you could use Java 8's fancy lambda features, or you could do it the old way and just define an interface that calls the function. Something like this:

    interface Caller{
       void call();
    }
    
    Caller callsReset = new Caller(){
       void call(){
          reset();
       }
    }
    
    callsReset.call(); //calls the reset() function
    
Sign In or Register to comment.