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?

7
  • Did you try Command pattern? en.wikipedia.org/wiki/Command_pattern Commented Feb 21, 2018 at 9:44
  • Any guide for that? How about Callable <T>? Commented Feb 21, 2018 at 9:45
  • What did you try so far? Can you elaborate? There are multiple patterns and Callable<T> might be one of it. Function<T, R> 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. Commented Feb 21, 2018 at 9:46
  • Have a look at this and this Commented Feb 21, 2018 at 9:47
  • I tried Callable <T> but there is an error while I am trying it. Do I need to put my sample code in my question? Commented Feb 21, 2018 at 9:48

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I'd rather use Function than Runnable, better typing.
@lexicore they're different functional interfaces. You can't simply substitute one for another. I chose Runnable here because it's the simplest.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.