首页 > 解决方案 > 为什么 Robot.delay(int ms) 限制为 1 分钟?

问题描述

执行我的软件时出现以下异常:

Exception in thread "main" java.lang.IllegalArgumentException: Delay must be to 0 to 60,000ms
    at java.awt.Robot.checkDelayArgument(Robot.java:544)
    at java.awt.Robot.delay(Robot.java:534)
    at com.company.Main.main(Main.java:10)

令我惊讶的是,有睡眠时间限制,标准库异常消息的语法错误/错字(to 0 to?)。检查该delay()方法的源代码后,我注意到它限制了等待时间,如异常所述:

/**
 * Sleeps for the specified time.
 * To catch any <code>InterruptedException</code>s that occur,
 * <code>Thread.sleep()</code> may be used instead.
 * @param   ms      time to sleep in milliseconds
 * @throws  IllegalArgumentException if <code>ms</code> is not between 0 and 60,000 milliseconds inclusive
 * @see     java.lang.Thread#sleep
 */
public synchronized void delay(int ms) {
    checkDelayArgument(ms);
    try {
        Thread.sleep(ms);
    } catch(InterruptedException ite) {
        ite.printStackTrace();
    }
}

private static final int MAX_DELAY = 60000;

private void checkDelayArgument(int ms) {
    if (ms < 0 || ms > MAX_DELAY) {
        throw new IllegalArgumentException("Delay must be to 0 to 60,000ms");
    }
}

为什么要这样做?这似乎是糟糕的 API 设计。InterruptedException除了为您捕获冗余检查异常并同步调用之外,它还有什么用途?

标签: javaapi-designawtrobot

解决方案


除了原始开发人员之外,没有人可以回答这个问题。

你可以很清楚地看到它所做的只是 call Thread::sleep,所以只需做同样的事情。你不需要打电话Robot::delay

以下是完全等价的,没有任意限制

Robot r;
long sleepDuration = 60001;
synchronized (r) {
    try {
        Thread.sleep(sleepDuration);
    } catch(InterruptedException ite) {
        ite.printStackTrace();
    }
}

看起来 API 设计很差

这个班19岁。JDK 中有很多糟糕的设计决策,尤其是在较旧的东西中。


推荐阅读