Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do you bind a function in hashmap

Tags:

java

hashmap

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?

like image 601
dj buen Avatar asked Mar 04 '26 13:03

dj buen


2 Answers

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?

like image 152
Savino Sguera Avatar answered Mar 06 '26 04:03

Savino Sguera


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.

like image 35
Sanjay T. Sharma Avatar answered Mar 06 '26 04:03

Sanjay T. Sharma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!