Ryan
Ryan

Reputation: 747

Android/Java: Is there a way to store a method?

So I have a loop class that is basically as follows:

public class Loop extends Thread {
    private boolean running;

    public Loop() {
        running = false;
    }

    public void run() {
        while(running) {
            //Do stuff
        }
    }

    public void setRunning(boolean b) {
        running = b;
    }
}

What I'd like to know is whether or not it is possible to store methods. For example the class could look like this instead.

public class Loop extends Thread {
    private boolean running;
    private Method method;

    public Loop() {
        running = false;
    }

    public void run() {
        while(running) {
            if(method != null)
                method.callMethod();
        }
    }

    public void setRunning(boolean b) {
        running = b;
    }

    public void setMethod(Method m) {
        method = m;
    }
}

Is anything like this possible?

Upvotes: 0

Views: 63

Answers (1)

Bob
Bob

Reputation: 13865

I assume you want this functionality in Java 6, so you can use interface and anonymous class.

Interface code:

public interface Listener {
    void callMethod();
}

Your Thread:

public class Loop extends Thread {
    private boolean running;
    private Listener listener;

    public Loop() {
        running = false;
    }

    public void run() {
        while(running) {
            if(listener != null)
                listener.callMethod();
        }
    }

    public void setRunning(boolean b) {
        running = b;
    }

    public void setListener(Listener listener) {
        this.listener = listener;
    }
}

Set Listener:

Loop loop = new Loop();

loop.setListener(new Listener() {
    @Override
    public void callMethod() {
    // Do stuff
    }
});

This will work for your usecase. If you want to save methods and pass methods as data, you have to either use Java 8 (not supported on all Android API levels) or Kotlin.

Upvotes: 4

Related Questions