Is there a way to bind parameters parameters to function pointers in Java like you can with std::bind in C++? What would the Java equivalent of something like this be?
void PrintStringInt(const char * s, int n)
{
std::cout << s << ", " << n << std::endl;
}
void PrintStringString(const char * s, const char * s2)
{
std::cout << s << ", " << s2 << std::endl;
}
int main()
{
std::vector<std::function<void(const char *)>> funcs;
funcs.push_back(std::bind(&PrintStringInt, std::placeholders::_1, 4));
funcs.push_back(std::bind(&PrintStringString, std::placeholders::_1, "bar"));
for(auto i = funcs.begin(); i != funcs.end(); ++i){
(*i)("foo");
}
return 0;
}
You can create an anonymous class with a function of the desired signature, that forwards calls to the original function.
Let's say you have these functions:
Then you can create anonymous classes that effectively bind arguments to these functions.
From Java7 on, one could do the same also with method handles, see the API doc of class
java.lang.invoke.MethodHandle
for details.This is as close as I think you can get to a line by line translation,
bind
does not map 1:1 to any Java construct;I'm afraid not, but this code is an approach to mimic the C++ templates (poorly):
Outputs:
Use MethodHandle, here is an example