Reputation: 208
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?
Upvotes: 2
Views: 364
Reputation: 3572
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?
Upvotes: 3
Reputation: 20081
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.
Upvotes: 1
Reputation: 14077
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.
Upvotes: 1
Reputation: 15729
You could do it if all the functions implemented the same Interface. Which doesn't seem to be the case for you.
Upvotes: 2
Reputation: 38541
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);
}
Upvotes: 2
Reputation: 23218
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.
Upvotes: 2