java - 为什么 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
除了为您捕获冗余检查异常并同步调用之外,它还有什么用途?
解决方案
除了原始开发人员之外,没有人可以回答这个问题。
你可以很清楚地看到它所做的只是 call Thread::sleep
,所以只需做同样的事情。你不需要打电话Robot::delay
。
以下是完全等价的,没有任意限制
Robot r;
long sleepDuration = 60001;
synchronized (r) {
try {
Thread.sleep(sleepDuration);
} catch(InterruptedException ite) {
ite.printStackTrace();
}
}
看起来 API 设计很差
这个班19岁。JDK 中有很多糟糕的设计决策,尤其是在较旧的东西中。
推荐阅读
- ruby - 如何轻松查看未修补插件的服务器安装依赖项?
- pine-script - 从特定 bar_index 获取收盘价?
- google-chrome - Chrome devtools 在被忽略的脚本中错误地暂停异常
- javascript - 提取条件逻辑以分离 React 组件
- r - 基于另一个数据帧更新 R 中的数据帧
- javascript - 如何在 TypeScript 中创建 RequireOnlyOne 嵌套类型?
- generics - 我可以在 Rust 中命名约束吗?
- php - “preg_match_all() 期望参数 2 为字符串,资源给定” 使用 PHPMailer 和 posgresql 发送电子邮件时出错
- javascript - 当某些数字在列表之间打乱时如何重新计算范围
- javascript - 如何在浏览器中以 TLS 连接到 MQTT 代理(React、Vue)