By Bill the Lizard


2008-09-23 17:20:10 8 Comments

I have a method that's about ten lines of code. I want to create more methods that do exactly the same thing, except for a small calculation that's going to change one line of code. This is a perfect application for passing in a function pointer to replace that one line, but Java doesn't have function pointers. What's my best alternative?

21 comments

@mrts 2016-10-07 17:08:44

None of the Java 8 answers have given a full, cohesive example, so here it comes.

Declare the method that accepts the "function pointer" as follows:

void doCalculation(Function<Integer, String> calculation, int parameter) {
    final String result = calculation.apply(parameter);
}

Call it by providing the function with a lambda expression:

doCalculation((i) -> i.toString(), 2);

@i_am_zero 2015-06-23 11:06:06

Prior to Java 8, nearest substitute for function-pointer-like functionality was an anonymous class. For example:

Collections.sort(list, new Comparator<CustomClass>(){
    public int compare(CustomClass a, CustomClass b)
    {
        // Logic to compare objects of class CustomClass which returns int as per contract.
    }
});

But now in Java 8 we have a very neat alternative known as lambda expression, which can be used as:

list.sort((a, b) ->  { a.isBiggerThan(b) } );

where isBiggerThan is a method in CustomClass. We can also use method references here:

list.sort(MyClass::isBiggerThan);

@sblundy 2008-09-23 17:21:43

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);

@Ogre Psalm33 2008-10-09 16:55:59

This is an example of the "Command Patern", by the way. en.wikipedia.org/wiki/Command_Pattern

@Rory O'Kane 2011-12-31 07:39:17

@Ogre Psalm33 This technique could also be the Strategy Pattern, depending on how you use it. The difference between the Strategy Pattern and the Command Pattern.

@momomo 2012-09-29 21:18:51

Here is a closure implementation for Java 5, 6, and 7 mseifed.blogspot.se/2012/09/… It contains all one could ask for... I think it is pretty awesome!

@Lawrence Dol 2014-09-17 21:50:26

@SecretService: That link is dead.

@momomo 2014-09-23 14:36:43

@LawrenceDol Yeah, it is. Here is a pastebin of the class that I am using. pastebin.com/b1j3q2Lp

@momomo 2014-10-16 11:12:15

@LawrenceDol Here it is, it has different name now, also all of the versions orignally present are not there ( to support non-final access and more through abstract classes, it might be added again for < Java 8 versions, what platform are you looking for?) : bitbucket.org/momomo/opensource/src

@ToolmakerSteve 2015-09-05 16:57:14

@momo - That version is not compatible with Java 7 (for Android development, building to an older Android API, for legacy reasons). Errors are Default methods are allowed only at source level 1.8 or above and Lambda expressions are allowed only at source level 1.8 or above. Do you have a Java 7 compatible version available?

@momomo 2015-09-07 06:34:55

@ToolmakerSteve I think it's just a matter of removing the 'default' methods in there, which i have added in my own code since... bitbucket.org/momomo/opensource/src/…

@Alex 2015-05-10 12:50:18

Since Java8, you can use lambdas, which also have libraries in the official SE 8 API.

Usage: You need to use a interface with only one abstract method. Make an instance of it (you may want to use the one java SE 8 already provided) like this:

Function<InputType, OutputType> functionname = (inputvariablename) {
... 
return outputinstance;
}

For more information checkout the documentation: https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

@user3002379 2014-08-19 10:43:24

New Java 8 Functional Interfaces and Method References using the :: operator.

Java 8 is able to maintain method references ( MyClass::new ) with "@ Functional Interface" pointers. There are no need for same method name, only same method signature required.

Example:

@FunctionalInterface
interface CallbackHandler{
    public void onClick();
}

public class MyClass{
    public void doClick1(){System.out.println("doClick1");;}
    public void doClick2(){System.out.println("doClick2");}
    public CallbackHandler mClickListener = this::doClick;

    public static void main(String[] args) {
        MyClass myObjectInstance = new MyClass();
        CallbackHandler pointer = myObjectInstance::doClick1;
        Runnable pointer2 = myObjectInstance::doClick2;
        pointer.onClick();
        pointer2.run();
    }
}

So, what we have here?

  1. Functional Interface - this is interface, annotated or not with @FunctionalInterface, which contains only one method declaration.
  2. Method References - this is just special syntax, looks like this, objectInstance::methodName, nothing more nothing less.
  3. Usage example - just an assignment operator and then interface method call.

YOU SHOULD USE FUNCTIONAL INTERFACES FOR LISTENERS ONLY AND ONLY FOR THAT!

Because all other such function pointers are really bad for code readability and for ability to understand. However, direct method references sometimes come handy, with foreach for example.

There are several predefined Functional Interfaces:

Runnable              -> void run( );
Supplier<T>           -> T get( );
Consumer<T>           -> void accept(T);
Predicate<T>          -> boolean test(T);
UnaryOperator<T>      -> T apply(T);
BinaryOperator<T,U,R> -> R apply(T, U);
Function<T,R>         -> R apply(T);
BiFunction<T,U,R>     -> R apply(T, U);
//... and some more of it ...
Callable<V>           -> V call() throws Exception;
Readable              -> int read(CharBuffer) throws IOException;
AutoCloseable         -> void close() throws Exception;
Iterable<T>           -> Iterator<T> iterator();
Comparable<T>         -> int compareTo(T);
Comparator<T>         -> int compare(T,T);

For earlier Java versions you should try Guava Libraries, which has similar functionality, and syntax, as Adrian Petrescu has mentioned above.

For additional research look at Java 8 Cheatsheet

and thanks to The Guy with The Hat for the Java Language Specification §15.13 link.

@Lawrence Dol 2014-09-17 21:53:45

"Because all other ... are really bad for code readability" is a completely baseless claim, and wrong, besides.

@vwvan 2011-03-18 02:53:57

To do the same thing without interfaces for an array of functions:

class NameFuncPair
{
    public String name;                // name each func
    void   f(String x) {}              // stub gets overridden
    public NameFuncPair(String myName) { this.name = myName; }
}

public class ArrayOfFunctions
{
    public static void main(String[] args)
    {
        final A a = new A();
        final B b = new B();

        NameFuncPair[] fArray = new NameFuncPair[]
        {
            new NameFuncPair("A") { @Override void f(String x) { a.g(x); } },
            new NameFuncPair("B") { @Override void f(String x) { b.h(x); } },
        };

        // Go through the whole func list and run the func named "B"
        for (NameFuncPair fInstance : fArray)
        {
            if (fInstance.name.equals("B"))
            {
                fInstance.f(fInstance.name + "(some args)");
            }
        }
    }
}

class A { void g(String args) { System.out.println(args); } }
class B { void h(String args) { System.out.println(args); } }

@ToolmakerSteve 2015-09-05 15:45:52

Why? This is more complicated than previously proposed solutions, which simply need one anonymous function definition per alternative. Per alternative, you create a class and an anonymous function definition. Worse, this is done in two different locations in the code. You might want to provide some justification for using this approach.

@Scott Emmons 2014-06-10 23:02:32

If anyone is struggling to pass a function that takes one set of parameters to define its behavior but another set of parameters on which to execute, like Scheme's:

(define (function scalar1 scalar2)
  (lambda (x) (* x scalar1 scalar2)))

see Pass Function with Parameter-Defined Behavior in Java

@Blair Conrad 2008-09-23 17:27:06

For each "function pointer", I'd create a small functor class that implements your calculation. Define an interface that all the classes will implement, and pass instances of those objects into your larger function. This is a combination of the "command pattern", and "strategy pattern".

@sblundy's example is good.

@The Guy with The Hat 2014-02-23 20:37:30

Method references using the :: operator

You can use method references in method arguments where the method accepts a functional interface. A functional interface is any interface that contains only one abstract method. (A functional interface may contain one or more default methods or static methods.)

IntBinaryOperator is a functional interface. Its abstract method, applyAsInt, accepts two ints as its parameters and returns an int. Math.max also accepts two ints and returns an int. In this example, A.method(Math::max); makes parameter.applyAsInt send its two input values to Math.max and return the result of that Math.max.

import java.util.function.IntBinaryOperator;

class A {
    static void method(IntBinaryOperator parameter) {
        int i = parameter.applyAsInt(7315, 89163);
        System.out.println(i);
    }
}
import java.lang.Math;

class B {
    public static void main(String[] args) {
        A.method(Math::max);
    }
}

In general, you can use:

method1(Class1::method2);

instead of:

method1((arg1, arg2) -> Class1.method2(arg1, arg2));

which is short for:

method1(new Interface1() {
    int method1(int arg1, int arg2) {
        return Class1.method2(arg1, agr2);
    }
});

For more information, see :: (double colon) operator in Java 8 and Java Language Specification §15.13.

@yogibimbi 2011-11-09 14:59:09

oK, this thread is already old enough, so very probably my answer is not helpful for the question. But since this thread helped me to find my solution, I'll put it out here anyway.

I needed to use a variable static method with known input and known output (both double). So then, knowing the method package and name, I could work as follows:

java.lang.reflect.Method Function = Class.forName(String classPath).getMethod(String method, Class[] params);

for a function that accepts one double as a parameter.

So, in my concrete situation I initialized it with

java.lang.reflect.Method Function = Class.forName("be.qan.NN.ActivationFunctions").getMethod("sigmoid", double.class);

and invoked it later in a more complex situation with

return (java.lang.Double)this.Function.invoke(null, args);

java.lang.Object[] args = new java.lang.Object[] {activity};
someOtherFunction() + 234 + (java.lang.Double)Function.invoke(null, args);

where activity is an arbitrary double value. I am thinking of maybe doing this a bit more abstract and generalizing it, as SoftwareMonkey has done, but currently I am happy enough with the way it is. Three lines of code, no classes and interfaces necessary, that's not too bad.

@yogibimbi 2011-11-18 15:28:59

thanks Rob for adding the code markdown, I was too impatient and stupid to find it;-)

@Robert 2011-03-02 04:11:04

Wow, why not just create a Delegate class which is not all that hard given that I already did for java and use it to pass in parameter where T is return type. I am sorry but as a C++/C# programmer in general just learning java, I need function pointers because they are very handy. If you are familiar with any class which deals with Method Information you can do it. In java libraries that would be java.lang.reflect.method.

If you always use an interface, you always have to implement it. In eventhandling there really isn't a better way around registering/unregistering from the list of handlers but for delegates where you need to pass in functions and not the value type, making a delegate class to handle it for outclasses an interface.

@ToolmakerSteve 2015-09-05 15:47:13

Not a useful answer, unless you show code details. How does creating a Delegate class help? What code is required per alternative?

@Adrian Petrescu 2010-12-16 21:32:14

The Google Guava libraries, which are becoming very popular, have a generic Function and Predicate object that they have worked into many parts of their API.

@ToolmakerSteve 2015-09-05 15:40:22

This answer would be more useful if it gave code details. Take the code shown in the accepted answer, and show how it would look using Function.

@Bill K 2010-05-04 18:44:01

@sblundy's answer is great, but anonymous inner classes have two small flaws, the primary being that they tend not to be reusable and the secondary is a bulky syntax.

The nice thing is that his pattern expands into full classes without any change in the main class (the one performing the calculations).

When you instantiate a new class you can pass parameters into that class which can act as constants in your equation--so if one of your inner classes look like this:

f(x,y)=x*y

but sometimes you need one that is:

f(x,y)=x*y*2

and maybe a third that is:

f(x,y)=x*y/2

rather than making two anonymous inner classes or adding a "passthrough" parameter, you can make a single ACTUAL class that you instantiate as:

InnerFunc f=new InnerFunc(1.0);// for the first
calculateUsing(f);
f=new InnerFunc(2.0);// for the second
calculateUsing(f);
f=new InnerFunc(0.5);// for the third
calculateUsing(f);

It would simply store the constant in the class and use it in the method specified in the interface.

In fact, if KNOW that your function won't be stored/reused, you could do this:

InnerFunc f=new InnerFunc(1.0);// for the first
calculateUsing(f);
f.setConstant(2.0);
calculateUsing(f);
f.setConstant(0.5);
calculateUsing(f);

But immutable classes are safer--I can't come up with a justification to make a class like this mutable.

I really only post this because I cringe whenever I hear anonymous inner class--I've seen a lot of redundant code that was "Required" because the first thing the programmer did was go anonymous when he should have used an actual class and never rethought his decision.

@ToolmakerSteve 2015-09-05 15:30:14

Huh? OP is talking about different calculations (algorithms; logic); you are showing different values (data). You do show a specific case where the difference can be incorporated into a value, but that is an unjustifiable simplification of the problem being posed.

@Lawrence Dol 2010-01-28 03:20:55

One of the things I really miss when programming in Java is function callbacks. One situation where the need for these kept presenting itself was in recursively processing hierarchies where you want to perform some specific action for each item. Like walking a directory tree, or processing a data structure. The minimalist inside me hates having to define an interface and then an implementation for each specific case.

One day I found myself wondering why not? We have method pointers - the Method object. With optimizing JIT compilers, reflective invocation really doesn't carry a huge performance penalty anymore. And besides next to, say, copying a file from one location to another, the cost of the reflected method invocation pales into insignificance.

As I thought more about it, I realized that a callback in the OOP paradigm requires binding an object and a method together - enter the Callback object.

Check out my reflection based solution for Callbacks in Java. Free for any use.

@Mario Fusco 2009-09-12 07:39:12

Check out lambdaj

http://code.google.com/p/lambdaj/

and in particular its new closure feature

http://code.google.com/p/lambdaj/wiki/Closures

and you will find a very readable way to define closure or function pointer without creating meaningless interface or use ugly inner classes

@javashlook 2009-03-27 00:16:31

When there is a predefined number of different calculations you can do in that one line, using an enum is a quick, yet clear way to implement a strategy pattern.

public enum Operation {
    PLUS {
        public double calc(double a, double b) {
            return a + b;
        }
    },
    TIMES {
        public double calc(double a, double b) {
            return a * b;
        }
    }
     ...

     public abstract double calc(double a, double b);
}

Obviously, the strategy method declaration, as well as exactly one instance of each implementation are all defined in a single class/file.

@Peter Lawrey 2009-03-26 21:56:05

If you have just one line which is different you could add a parameter such as a flag and a if(flag) statement which calls one line or the other.

@ToolmakerSteve 2015-09-05 15:27:10

javaslook's answer seems like a cleaner way to do this, if more than two calculation variants. Or if one wishes to embed the code into the method, then an enum for the different cases which the method handles, and a switch.

@Peter Lawrey 2015-09-05 15:37:45

@ToolmakerSteve true, although today you would use lambdas in Java 8.

@TofuBeer 2009-03-26 21:39:48

You can also do this (which in some RARE occasions makes sense). The issue (and it is a big issue) is that you lose all the typesafety of using a class/interface and you have to deal with the case where the method does not exist.

It does have the "benefit" that you can ignore access restrictions and call private methods (not shown in the example, but you can call methods that the compiler would normally not let you call).

Again, it is a rare case that this makes sense, but on those occasions it is a nice tool to have.

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

class Main
{
    public static void main(final String[] argv)
        throws NoSuchMethodException,
               IllegalAccessException,
               IllegalArgumentException,
               InvocationTargetException
    {
        final String methodName;
        final Method method;
        final Main   main;

        main = new Main();

        if(argv.length == 0)
        {
            methodName = "foo";
        }
        else
        {
            methodName = "bar";
        }

        method = Main.class.getDeclaredMethod(methodName, int.class);

        main.car(method, 42);
    }

    private void foo(final int x)
    {
        System.out.println("foo: " + x);
    }

    private void bar(final int x)
    {
        System.out.println("bar: " + x);
    }

    private void car(final Method method,
                     final int    val)
        throws IllegalAccessException,
               IllegalArgumentException,
               InvocationTargetException
    {
        method.invoke(this, val);
    }
}

@Bill K 2010-05-04 18:46:21

I use this for menu handling/GUIs sometimes because method syntax is so much simpler than anonymous inner class syntax. It's neat, but you are adding the complexity of reflection which some people don't want to dig into, so be damn sure you get it right and have clear, textual errors for every possible error condition.

@Luigi a.k.a. Rhys 2011-08-05 06:52:17

You can do it type safely using generics and you don't need reflection.

@TofuBeer 2011-09-05 17:57:37

I fail to see how using generics and not using reflection would let you call a method by a name contained in a String?

@ToolmakerSteve 2015-09-05 15:22:13

@LuigiPlinge - can you provide a code snippet of what you mean?

@Dennis S 2008-09-25 03:21:47

Sounds like a strategy pattern to me. Check out fluffycat.com Java patterns.

@Dave L. 2008-09-23 21:22:33

@mikera 2010-06-30 20:31:24

+1 for useful links, even though I think that adding closures to Java is completely unhelpful.

@rcreswick 2008-09-23 17:30:21

You need to create an interface that provides the function(s) that you want to pass around. eg:

/**
 * A simple interface to wrap up a function of one argument.
 * 
 * @author rcreswick
 *
 */
public interface Function1<S, T> {

   /**
    * Evaluates this function on it's arguments.
    * 
    * @param a The first argument.
    * @return The result.
    */
   public S eval(T a);

}

Then, when you need to pass a function, you can implement that interface:

List<Integer> result = CollectionUtilities.map(list,
        new Function1<Integer, Integer>() {
           @Override
           public Integer eval(Integer a) {
              return a * a;
           }
        });

Finally, the map function uses the passed in Function1 as follows:

   public static <K,R,S,T> Map<K, R> zipWith(Function2<R,S,T> fn, 
         Map<K, S> m1, Map<K, T> m2, Map<K, R> results){
      Set<K> keySet = new HashSet<K>();
      keySet.addAll(m1.keySet());
      keySet.addAll(m2.keySet());

      results.clear();

      for (K key : keySet) {
         results.put(key, fn.eval(m1.get(key), m2.get(key)));
      }
      return results;
   }

You can often use Runnable instead of your own interface if you don't need to pass in parameters, or you can use various other techniques to make the param count less "fixed" but it's usually a trade-off with type safety. (Or you can override the constructor for your function object to pass in the params that way.. there are lots of approaches, and some work better in certain circumstances.)

@tchrist 2010-11-30 19:46:39

This “answer” pertains more to the problem set than to the solution set.

Related Questions

Sponsored Content

58 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

33 Answered Questions

[SOLVED] What's the simplest way to print a Java array?

  • 2009-01-03 20:39:39
  • Alex Spurling
  • 2176208 View
  • 1853 Score
  • 33 Answer
  • Tags:   java arrays printing

55 Answered Questions

[SOLVED] How to create a memory leak in Java

65 Answered Questions

[SOLVED] How do I generate random integers within a specific range in Java?

  • 2008-12-12 18:20:57
  • user42155
  • 3922531 View
  • 3382 Score
  • 65 Answer
  • Tags:   java random integer

86 Answered Questions

[SOLVED] Is Java "pass-by-reference" or "pass-by-value"?

42 Answered Questions

[SOLVED] How do I convert a String to an int in Java?

36 Answered Questions

41 Answered Questions

[SOLVED] How do I efficiently iterate over each entry in a Java Map?

32 Answered Questions

[SOLVED] When to use LinkedList over ArrayList in Java?

11 Answered Questions

[SOLVED] How do function pointers in C work?

  • 2009-05-08 15:49:17
  • Yuval Adam
  • 774981 View
  • 1172 Score
  • 11 Answer
  • Tags:   c function-pointers

Sponsored Content