java Equals方法不能很好地处理Throwable
我有一些外部提供的回调要运行。由于它们可以包含任何内容,我更愿意冒险捕捉它们,从而从任何可恢复的错误中恢复
回调执行的某些阶段允许抛出错误,除非错误在一行中重复两次。在这种情况下,它们被标记为无效,除非用户手动启动,否则无法再运行
这就是处理以下问题的方法:
/**
* Sets whether the bot is disabled due to error or not. If error has occured during
* getWindow, the bot will be disabled immediatelly. If the error occured during canRun() or run()
* the bot will only be disabled if the error is repetitive.
* @param error error that occured
* @param phase phase of execution in which the error occured
* @return true if this error is not significant enough to cancel this bot
*/
public boolean continueOnError(Throwable error, ExecutionPhase phase) {
System.err.println("Error "+error+" caught in robot "+this.getClass().getName());
System.err.println("Last: "+lastError+((error.equals(lastError)?" which is the same as last":" which is defferent than last")));
if(phase == ExecutionPhase.GET_WINDOW || (error.equals(lastError) && phase==errorPhase)) {
//Remember last
setLastError(error, phase);
//If robot state listener is listening, inform it about this event
if(listener!=null)
listener.disabledByError(error);
//Disable the robot - on attempt to run, it will throw RobotDisabledException
return !(errorDisabled = true);
}
//Rememeber last
setLastError(error, phase);
//The robot can remain running, but next same error will turn it down
return true;
}
我知道这是一种原始的方法,但我需要从某个地方开始。这段代码的问题是Throwable
上的equals
方法总是返回false。请参见此方法生成的输出:
Error java.lang.Error: TEST ERROR caught in robot cz.autoclient.robots.LaunchBot
Last: java.lang.Error: TEST ERROR which is defferent than last
Error java.lang.Error: TEST ERROR caught in robot cz.autoclient.robots.LaunchBot
Last: java.lang.Error: TEST ERROR which is defferent than last
Error java.lang.Error: TEST ERROR caught in robot cz.autoclient.robots.LaunchBot
Last: java.lang.Error: TEST ERROR which is defferent than last
Error java.lang.Error: TEST ERROR caught in robot cz.autoclient.robots.LaunchBot
Last: java.lang.Error: TEST ERROR which is defferent than last
为什么会这样
# 1 楼答案
Throwable
不重写equals()
,问题在于Error
和LastError
实例可能是两个具有相同值的不同Throwable
实例