What's the nearest substitute for a function pointer in Java?
Anonymous inner class
Say you want to have a function passed in with a String
param that returns an int
.
First you have to define an interface with the function as its only member, if you can't reuse an existing one.
interface StringFunction {
int func(String param);
}
A method that takes the pointer would just accept StringFunction
instance like so:
public void takingMethod(StringFunction sf) {
int i = sf.func("my string");
// do whatever ...
}
And would be called like so:
ref.takingMethod(new StringFunction() {
public int func(String param) {
// body
}
});
EDIT: In Java 8, you could call it with a lambda expression:
ref.takingMethod(param -> bodyExpression);
how to implement Java equivalent of Function Pointers via abstract classes
While that's decent (aside from not having constructors that work right) I'd do it different, using anonymous classes.
abstract class Functor {
public abstract double compute(double a, double b);
public static void main(String[] args) {
Functor add = new Functor() {
// defining it here is essentially how you do a function pointer
public double compute(double a, double b) { return a + b; }
};
Functor subtract = new Functor() {
public double compute(double a, double b) { return a - b; }
};
System.out.println(add.compute(1.0,2.0));
System.out.println(subtract.compute(1.0,2.0));
}
}
Result:
C:\Documents and Settings\glowcoder\My Documents>java Functor
3.0
-1.0
C:\Documents and Settings\glowcoder\My Documents>
What is the cloest thing to a function pointer in java?
Until they add closures to java, the thing seems closest to java.lang.reflect.Method
. For example Method method = SomeClass.getMethod("methodName", methodParameterTypes)
Then you can pass the method
around (like a function pointer) and call invoke(..)
on it, passing an object (or null
if static)
But this is not quite a good practice. You can define an interface, or use an existing one Runnable
/ Callable
, implement it inline, and pass the instance.
Is there an equivalent to C++ member function pointers in Java?
No, there is simply no such thing in Java as a Function. There are only Objects and methods which are wholly owned by objects and subordinate to them. The object is your lord and master in java, nothing happens but through his will.
You can implement a sort of java-delegation by making your objects implement delegate interfaces, that's as close as it gets.
public interface Func {
boolean func(Foo foo);
}
public class Test1 implements Func {
@Override
public boolean func(Foo foo) {
return doSomeStuff();
}
...
_foos[0] = getTest(new Test1());
hope that's enough to get the idea across. In general you don't see that actually done much in application code.
edit:
Since you're new to Java, syntax to actually do what you were trying to do. Which may also illuminate what a pita it is and why people don't like it :)
public class Bar {
public static interface Func {
boolean func(Foo current, Foo other);
}
public static Func test1 = new Func() {
@Override
public boolean func(Foo current, Foo other) {
return current.test1(other);
}
};
public Bar doSomething() {
_foos = new Foo[4];
_foos[0] = getTest(test1);
//...
}
private Foo _getTest(Func func) {
Foo current = _foos[ 0 ];
for ( int i = 1; i != _foos.length; i++ ) {
current = func(current, _foos[ i ] ) ? _foos[ i ] : current;
}
return current;
}
}
Function Pointers in Java
The Java idiom for function-pointer-like functionality is an an anonymous class implementing an interface, e.g.
Collections.sort(list, new Comparator<MyClass>(){
public int compare(MyClass a, MyClass b)
{
// compare objects
}
});
Update: the above is necessary in Java versions prior to Java 8. Now we have much nicer alternatives, namely lambdas:
list.sort((a, b) -> a.isGreaterThan(b));
and method references:
list.sort(MyClass::isGreaterThan);
Simulate function pointer
How to make a callback in this case? I prefer to avoid such solution due to it's complexity and ugliness. Even if it is the least painful, I don't have an idea how to implement it here.
Since there are no function pointers in Java, you have to use a common interface instead. Your functions then have to be implementations of that interface. It is up to you whether you want to use names for those implementing classes (i.e. class F1 extends Function { … }
) or anonymous classes instead (i.e. new Function { … }
). It is also up to you whether you write the imp0lementation inside that class, or instead have the class implementation call one of your existing static functions.
Taking one example, with anonymous classes directly containing the implementation:
public class Integrals
{
public interface Function {
double eval(double x);
}
public static final Function f1 = new Function() {
public double eval(double x) {
return x*5+Math.sin(x);
}
};
public static final Function f2 = new Function() {
public double eval(double x) {
return Math.pow(x*f1.eval(-x),x);
}
};
public static double TrapezoidalIntegration(double a,double b,int n,Function f)
{
// … using f.eval(x) to compute values
Function Pointer in Java
Just pass an Interface which defines the authenticate
method.
void DoSomething(IAuthenticationProvider authProvider) {
// ...
authProvider.authenticate();
}
Function pointers/delegates in Java?
What about this one?
HashMap<Integer, Runnable> map = new HashMap<Integer, Runnable>();
map.put(Register.ID, new Runnable() {
public void run() { functionA(); }
});
map.put(NotifyMessage.ID, new Runnable() {
public void run() { functionB(); }
});
// ...
map.get(id).run();
(If you need to pass some arguments, define your own interface with a function having a suitable parameter, and use that instead of Runnable).
Related Topics
Is There a Performance Difference Between a for Loop and a For-Each Loop
Difference Between File.Separator and Slash in Paths
Convert Java.Util.Date to Java.Time.Localdate
Can't Add Value to the Java Collection with Wildcard Generic Type
Centering a Jlabel on a JPAnel
How to Set the Classpath in Netbeans
How to Make an Image Move While Listening to a Keypress in Java
Invalidkeyexception Illegal Key Size
How to Write a Custom JSON Deserializer for Gson
Swing Grouplayout: Resizing and Limiting Component Sizes
Why Can Outer Java Classes Access Inner Class Private Members
Reading a List from Properties File and Load with Spring Annotation @Value
What Is the Point of "Final Class" in Java
How to Map a Composite Key with JPA and Hibernate