2

Lets say for example we are gonna bind the function into a hashmap

if(identity.equals("printf")){
    doPrintf(statement);
}else if(identity.equals("scanf")){
    doScanf(statement);
}else if(identity.equals("puts")){
    doPuts(statement);
}else if (identity.equals("functioncall")){
    expectFunc  = true;
}else if (identity.equals("functioncallwithparams")){
    expectFunc  = true;
    expectParams = true;
}else if (identity.equals("assignment")){
    //doAssignment(statement);
    vartoupdate = statement;
    updateVar = true;
}else if(identity.equals("getch"))
    doGetch();

something like this HM.put("getch",doGetch()). How could you possibly do this?

charmae
  • 1,080
  • 14
  • 38
dj buen
  • 208
  • 1
  • 9

6 Answers6

3

If I get your question correctly, you want to call a method based on its name (or at least part of it). If so, you should look at the reflection API, there's a related question here on SO btw: How do I invoke a Java method when given the method name as a string?

Community
  • 1
  • 1
Savino Sguera
  • 3,522
  • 21
  • 20
2

If you can take the hit for creating a new object for each function, this can simply be achieved by creating a Function object for each function to be called and maintaining a mapping between the function name and it's corresponding function object.

public interface Function<T> {    
   public T apply(Object... vargs);    
}

Now just make every function object implement this interface, create new objects for each newly created class and stuff them in a map.

Sanjay T. Sharma
  • 22,857
  • 4
  • 59
  • 71
2
interface Func { 
    public void exec();
}

class GetCharFunc implements Func { 
   @Override
   public void exec() { 
       // implementation details
   }
}

Func currentFunc;

if(identity.equals("getch")) {
    currentFunc = new GetCharFunc();
    myMap.put("getch", currentFunc); 
}
Amir Afghani
  • 37,814
  • 16
  • 84
  • 124
2

You could do it if all the functions implemented the same Interface. Which doesn't seem to be the case for you.

user949300
  • 15,364
  • 7
  • 35
  • 66
1

Java does not support references to methods or functions as a language feature. You can either create a interface with one method and implement this multiple times with your different method invocations or use Reflection and put the java.lang.reflect.Method objects into your hash map.

x4u
  • 13,877
  • 6
  • 48
  • 58
1

If you're using Java 7, you can use a switch statement based on a String value. Here's a brief tutorial on that: Use String in the switch statement with Java 7

If Java 7 isn't an option I think the next best option is to switch on an enum. Here's a tutorial on enum types.

Perhaps if you explained what problem you're trying to solve you'd get better answers.

Paul
  • 19,704
  • 14
  • 78
  • 96