This may be something common and trivial, but I seem to be having trouble finding a concrete answer. In C# there is a concept of delegates, which relates strongly to the idea of function pointers from C++. Is there a similar functionality in Java? Given that pointers are somewhat absent, what is the best way about this? And to be clear, we're talking first class here.
-
1I am just curious as to why you would want this where listeners or other OOP construct would do the same task while retaining their object nature. I mean I understand the need for the functionality offered by the concept just that it can be achieved with plain object.. unless, of course I am missing something, hence my asking this question ! :-) – Newtopian Jul 02 '09 at 10:58
-
2Java 8 has lambda expressions: http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html You may want to check that out. Not quite a function pointer, but might still be of more use. – FrustratedWithFormsDesigner May 06 '14 at 19:51
-
6Java 8 method references is exactly what you are asking for. – Steven Jun 05 '14 at 08:23
-
9Java 8 [method references](http://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html) is exactly what you are asking for. `this::myMethod` is semantically the same as creating a lambda `paramA, paramB -> this.myMethod(paramA, paramB)`. – Steven Jun 05 '14 at 08:30
-
3possible duplicate of [What's the nearest substitute for a function pointer in Java?](http://stackoverflow.com/questions/122407/whats-the-nearest-substitute-for-a-function-pointer-in-java) – nawfal Jul 05 '14 at 07:19
12 Answers
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);

- 342,105
- 78
- 482
- 720
-
2The Strategy design pattern. Not as ugly as a C or C++ function pointer when you want the function to use some non global data that is not provided as an argument to the function. – Raedwald Jan 13 '11 at 21:41
-
78@Raedwald C++ has functors, and C++0x has closures and lambdas built on top of functors. It even has `std::bind`, which binds parameters to functions and returns a callable object. I can't defend C on these grounds, but C++ really _is_ better than Java for this. – zneak Mar 02 '11 at 04:48
-
-
22@zneak, @Raedwald: You can do this in C by passing along a pointer to user data (eg: struct). (and can encapsulate it with each new level of callback indirection) It's actually fairly clean. – brice Jun 10 '11 at 14:06
-
27Yeah, I'll actually take C function pointers over crufty wrapper classes any day – B T May 17 '12 at 02:26
-
3@Raedwald, that's what delegates in C# are for! They are clean, type-safe function pointers. – devinbost May 09 '14 at 06:51
-
3
You can substitue a function pointer with an interface. Lets say you want to run through a collection and do something with each element.
public interface IFunction {
public void execute(Object o);
}
This is the interface we could pass to some say CollectionUtils2.doFunc(Collection c, IFunction f).
public static void doFunc(Collection c, IFunction f) {
for (Object o : c) {
f.execute(o);
}
}
As an example say we have a collection of numbers and you would like to add 1 to every element.
CollectionUtils2.doFunc(List numbers, new IFunction() {
public void execute(Object o) {
Integer anInt = (Integer) o;
anInt++;
}
});

- 3,092
- 22
- 30
You can use reflection to do it.
Pass as parameter the object and the method name (as a string) and then invoke the method. For example:
Object methodCaller(Object theObject, String methodName) {
return theObject.getClass().getMethod(methodName).invoke(theObject);
// Catch the exceptions
}
And then use it as in:
String theDescription = methodCaller(object1, "toString");
Class theClass = methodCaller(object2, "getClass");
Of course, check all exceptions and add the needed casts.

- 29,846
- 15
- 139
- 192

- 465
- 4
- 2
-
7Reflection is not the right answer to anything except "How do I write slow dodgy java code" :D – Jay Aug 05 '13 at 12:34
-
5It might be "ugly" and slow, but I believe that reflection allows to do stuff that the interface-based solution in the accepted answer cannot do (unless I'm mistaken), namely call various methods of the same object within the same code portion. – Eusebius Apr 09 '14 at 06:50
-
@zoquete.. I was going through this post and had a doubt.. so in your approach, if i access the variable "theDescription", the function will be called each and everytime the variable is accessed?? – karthik27 Apr 16 '14 at 18:48
No, functions are not first class objects in java. You can do the same thing by implementing a handler class - this is how callbacks are implemented in the Swing etc.
There are however proposals for closures (the official name for what you're talking about) in future versions of java - Javaworld has an interesting article.

- 6,024
- 9
- 37
- 37
This brings to mind Steve Yegge's Execution in the Kingdom of Nouns. It basically states that Java needs an object for every action, and therefore does not have "verb-only" entities like function pointers.

- 20,565
- 5
- 44
- 69
To achieve similar functionality you could use anonymous inner classes.
If you were to define a interface Foo
:
interface Foo {
Object myFunc(Object arg);
}
Create a method bar
which will receive a 'function pointer' as an argument:
public void bar(Foo foo) {
// .....
Object object = foo.myFunc(argValue);
// .....
}
Finally call the method as follows:
bar(new Foo() {
public Object myFunc(Object arg) {
// Function code.
}
}

- 2,281
- 1
- 16
- 19
Java8 has introduced lambdas and method references. So if your function matches a functional interface (you can create your own) you can use a method reference in this case.
Java provides a set of common functional interfaces. whereas you could do the following:
public class Test {
public void test1(Integer i) {}
public void test2(Integer i) {}
public void consumer(Consumer<Integer> a) {
a.accept(10);
}
public void provideConsumer() {
consumer(this::test1); // method reference
consumer(x -> test2(x)); // lambda
}
}

- 24,223
- 14
- 73
- 76
-
is there the concept of an `alias`: e.g. `public List
collect(T t) = Collections::collect` – WestCoastProjects Jan 05 '20 at 19:50 -
There is no such thing in Java. You will need to wrap your function into some object and pass the reference to that object in order to pass the reference to the method on that object.
Syntactically, this can be eased to a certain extent by using anonymous classes defined in-place or anonymous classes defined as member variables of the class.
Example:
class MyComponent extends JPanel {
private JButton button;
public MyComponent() {
button = new JButton("click me");
button.addActionListener(buttonAction);
add(button);
}
private ActionListener buttonAction = new ActionListener() {
public void actionPerformed(ActionEvent e) {
// handle the event...
// note how the handler instance can access
// members of the surrounding class
button.setText("you clicked me");
}
}
}

- 4,091
- 3
- 19
- 29

- 17,651
- 15
- 54
- 58
I have implemented callback/delegate support in Java using reflection. Details and working source are available on my website.
How It Works
We have a principle class named Callback with a nested class named WithParms. The API which needs the callback will take a Callback object as a parameter and, if neccessary, create a Callback.WithParms as a method variable. Since a great many of the applications of this object will be recursive, this works very cleanly.
With performance still a high priority to me, I didn't want to be required to create a throwaway object array to hold the parameters for every invocation - after all in a large data structure there could be thousands of elements, and in a message processing scenario we could end up processing thousands of data structures a second.
In order to be threadsafe the parameter array needs to exist uniquely for each invocation of the API method, and for efficiency the same one should be used for every invocation of the callback; I needed a second object which would be cheap to create in order to bind the callback with a parameter array for invocation. But, in some scenarios, the invoker would already have a the parameter array for other reasons. For these two reasons, the parameter array did not belong in the Callback object. Also the choice of invocation (passing the parameters as an array or as individual objects) belongs in the hands of the API using the callback enabling it to use whichever invocation is best suited to it's inner workings.
The WithParms nested class, then, is optional and serves two purposes, it contains the parameter object array needed for the callback invocations, and it provides 10 overloaded invoke() methods (with from 1 to 10 parameters) which load the parameter array and then invoke the callback target.

- 63,018
- 25
- 139
- 189
Check the closures how they have been implemented in the lambdaj library. They actually have a behavior very similar to C# delegates:

- 13,548
- 3
- 28
- 37
Relative to most people here I am new to java but since I haven't seen a similar suggestion I have another alternative to suggest. Im not sure if its a good practice or not, or even suggested before and I just didn't get it. I just like it since I think its self descriptive.
/*Just to merge functions in a common name*/
public class CustomFunction{
public CustomFunction(){}
}
/*Actual functions*/
public class Function1 extends CustomFunction{
public Function1(){}
public void execute(){...something here...}
}
public class Function2 extends CustomFunction{
public Function2(){}
public void execute(){...something here...}
}
.....
/*in Main class*/
CustomFunction functionpointer = null;
then depending on the application, assign
functionpointer = new Function1();
functionpointer = new Function2();
etc.
and call by
functionpointer.execute();

- 6,079
- 2
- 30
- 45
Using interfaces in order to send functions as parameters can only be considered to be a workaround since any other language would use a function pointer/reference.
Your question is not exactly clear but here is how you can precisely send a function reference in Java:
import java.util.Arrays;
import java.util.function.Function;
public class FunctionPointerDemo2 {
static int increment(int n) {
return n + 1;
}
static void myObjective(int[] arr, Function<Integer, Integer> f) {
for (int i = 0; i < arr.length; ++i) {
arr[i] = f.apply(arr[i]);
}
}
public static void main(String[] args) {
int[] arr = {0, 1, 2, 3, 4};
myObjective(arr, FunctionPointerDemo2::increment);
System.out.println(Arrays.toString(arr));
}
}

- 82
- 12