1

I'm writing a program and I want to know if I can pass a method as a parameter of another method. For example, something of the following:

public boolean update(Method m){ //input is a method
    int i = m.execute();
    // logic relating to the value of i
}

I want to know if I can do this in java. I'm currently reading about functional programming and Reflection right now.

user3642365
  • 549
  • 1
  • 6
  • 16
  • 1
    Are you able to use Java 8? It adds support for lambda expressions, which makes functional programming a lot easier. If not, then reflection is the way to do what you're asking. – Andrew Williamson Apr 24 '16 at 01:07
  • I gather from your question that you haven't tried to create a simple program to try it out? Even if it doesn't work, it makes for a better question when you write code, test it, and tell us about the result. See http://stackoverflow.com/help/mcve – Hank D Apr 24 '16 at 01:10
  • Yes. Lambdas are very useful and offer some functional programming capabilities in Java – Logan Apr 24 '16 at 01:10
  • See this https://stackoverflow.com/questions/4685563/how-to-pass-a-function-as-a-parameter-in-java – sebenalern Apr 24 '16 at 01:11

2 Answers2

2

This has nothing to do with reflection, but you can pass "method references" if you are using java 8+. Assuming from your example that you intend to use methods that take no parameters and just return an int, you could do this:

public class MyClass {
    public int getIntMemberFunction(){ ... }
    public static int getIntStaticFunction(){ ... }
}

with your update function modified to look like this,

public boolean update(IntSupplier s){ //input is a method reference or lambda
    int i = s.get();
    // logic relating to the value of i
}

Then you could call update passing in a reference to any static function on any class as long as it takes no parameters and returns an int, like this:

boolean result = update(MyClass::getIntStaticFunction);

or you could call update passing in a reference to any member function of a specific object as long as it takes no parameters and returns an int, like this:

MyClass myClassInstance = ...
boolean result = update(myClassInstance::getIntMemberFunction);

If you want to add methods that take 1 or 2 parameters, you could create versions of update that take ToIntFunction or ToIntBiFunction. Beyond 2 parameters you would have to add your own functional interfaces.

Hank D
  • 6,271
  • 2
  • 26
  • 35
0

One way to do it is to use Interfaces. In Java you can pass as argument to a function an object that implements a particular interface and thus you can call that method on that object. More modern languages, such as Python, Swift, Javascript, have better support for this idiom.

Cyb3rFly3r
  • 1,321
  • 7
  • 12