D
D
D7ILeucoH2019-06-30 12:52:01
Java
D7ILeucoH, 2019-06-30 12:52:01

How is passing a function to a Java object implemented?

An object of a simple class is created: At the same level, there is a method
MediaProfiler profiler = new MediaProfiler();

void f() {
        Log.e("TAG", "d");
}

How can I pass the "f()" method to the "profiler" object?
Speaking in pseudocode, it is possible through such an unusual implementation:
void f() {
        Log.e("TAG", "d");
}
private void spot() {
        profiler = new MediaProfiler();
        profiler.onRun=f; //но не работает
}
public class MediaProfiler {

    public MediaProfiler() {
    //...
    }

    public void onRun() {
    //изменится после изменения
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2019-06-30
@D7ILeucoH

class SomeClass {
    void f() {
        Log.e("TAG", "d");
    }

    private void spot() {
        profiler = new MediaProfiler();
        profiler.onRun(SomeClass::f);
    }
}

public class MediaProfiler {
    public void onRun(Runnable f) {
        f.run()
    }
}

Relevant section of the documentation.

R
roxik, 2017-09-06
@blazer05

Add styles to the picture:

display: inline-block;
vertical-align: bottom;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question