Как проверить, что метод находится в очереди на выполнение в Java? - PullRequest
1 голос
/ 01 апреля 2020

У меня есть класс с методом sampleMethod. Как проверить, есть ли у объекта класса sampleMethod () и вызван ли sampleMethod (), а также отменить ли его выполнение?

public class MyClass {

    public checkMethodIsQueuedForExecution() {
        Method m = this.getClass().getMethod("sampleMethod");

        // Check if previously called, and stop it.

        if (m != null) {
            m.invoke(this, null); // calls sampleMethod()
        }
    }

    public void sampleMethod() {
        // do something
    }
}

Я выяснил, что могу проверить, что объект класса имеет метод используя отражение, но как проверить, стоит ли этот метод в очереди на выполнение? если да, то отмените его исполнение.

1 Ответ

1 голос
/ 02 апреля 2020

Вы ищете такой пример?

    // instance variable will control only if this instance's method 
    // was executed or not
    private volatile boolean isQueued = false;

    public void checkMethodIsQueuedForExecution() 
                throws NoSuchMethodException, SecurityException,
                       IllegalAccessException, IllegalArgumentException, 
                       InvocationTargetException {

        Method m = this.getClass().getMethod("sampleMethod");
        if (null == m) {
            return;
        }

        // Check if this instance's method previously called, and stop it.
        synchronized(this) { 
            if (isQueued) {
                return;
            }
            isQueued = true;

            m.invoke(this, null); // calls sampleMethod()

        }

    }
...