【问题标题】:How do I check that a method is queued for execution in Java?如何检查方法是否在 Java 中排队等待执行?
【发布时间】:2020-04-01 07:08:56
【问题描述】:

我有一个带有方法 sampleMethod 的类。如何检查一个类的 Object 是否有 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
    }
}

我发现我可以使用反射检查类的对象是否有方法,但是如何检查该方法是否排队等待执行?如果是,则取消它的执行。

【问题讨论】:

  • 听起来像XY Problem。为什么要这样做?
  • 这类似于objective-C有cancelPreviousPerformRequestsWithTarget,performSelector。我正在尝试为 Android 应用程序的 Java 找到相同的机制。
  • 我没有使用 Objective-C 的经验,但是查看这些方法的文档表明您正在以错误的方式进行操作。调用方法是立即的。反射在这里帮不了你。无论您使用什么 API,都应该提供一种取消异步请求的方法。也许如果你提供了一个 minimal reproducible example 来展示你所追求的以及你遇到的问题,那么某人可能会提供更多帮助。
  • Re, "//检查之前是否调用过,并停止它。"为什么不直接写sampleMethod() 让它只工作一次呢?

标签: java android multithreading handler runnable


【解决方案1】:

你在寻找这样的例子吗?

    // 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()

        }

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-30
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-26
    • 1970-01-01
    相关资源
    最近更新 更多