0

What I would like to do is send a function as parameter to other class' function. For example, I have UI.java class for UI and Timer.java class for the logic. So I would like to pass function of logic class to UI so that once a button is clicked, it will call function from Timer.java.

How can I do that? Is it recommended? standard for application development?

Michael
  • 41,989
  • 11
  • 82
  • 128
JMA
  • 974
  • 3
  • 13
  • 41
  • Did you try Command pattern? https://en.wikipedia.org/wiki/Command_pattern – h__ Feb 21 '18 at 09:44
  • Any guide for that? How about Callable ? – JMA Feb 21 '18 at 09:45
  • What did you try so far? Can you elaborate? There are multiple patterns and `Callable` might be one of it. `Function` might be an alternative and there are a lot of others - it all depends on what you're actually trying to do and what your code looks like. – Thomas Feb 21 '18 at 09:46
  • Have a look at [this](https://stackoverflow.com/questions/2186931/java-pass-method-as-parameter) and [this](https://stackoverflow.com/questions/1073358/function-pointers-in-java) – Abhi Feb 21 '18 at 09:47
  • I tried Callable but there is an error while I am trying it. Do I need to put my sample code in my question? – JMA Feb 21 '18 at 09:48
  • @Abhi Yellow quote blocks are for quotations, not for emphasis. Use bold text or italics for emphasis. But only edit a post if you can objectively improve it. Don't just do it because you feel like it. Sure, no worries. – Michael Feb 21 '18 at 09:58
  • See also: https://stackoverflow.com/questions/2186931/java-pass-method-as-parameter – lexicore Feb 21 '18 at 11:17

1 Answers1

0

Use a functional interface such as Runnable and a method reference:

class Bar
{
    public void doSomething() { /* ... */ }
}

class Foo
{
    private Runnable runnable;

    Foo(Runnable runnable)
    {
        this.runnable = runnable;
    }

    public void onCompletion()
    {
        this.runnable.run();
    }
}

Bar bar = new Bar();
Foo foo = new Foo(bar::doSomething);
foo.onCompletion();

The exact functional interface you'll want will depend on your use case. Have a look in the package java.util.function to find the one you need.

Michael
  • 41,989
  • 11
  • 82
  • 128
  • I'd rather use `Function` than `Runnable`, better typing. – lexicore Feb 21 '18 at 11:18
  • @lexicore they're different functional interfaces. You can't simply substitute one for another. I chose Runnable here because it's the simplest. – Michael Feb 22 '18 at 10:57