我确定这是一个非常愚蠢的问题,但我仍然想知道,是否可以动态地转换全局变量cause
,换句话说,不使用instanceof
运算符?
这个问题的原因是,我觉得instanceof
运算符在这里没有做任何好事,它只是静态地转换cause
,但在任何一种情况下它都在创建new IOException(cause)
< / p>
由于cause
的类型为Object
,因此我必须将其转换为String
或Throwable
。
private Object cause; // global variable
//...
if (failed)
throw cause instanceof String ? new IOException((String) cause) : new IOException((Throwable) cause);
下面是实际的代码片段,其中两个被重写的方法将被异步调用。
public class Command implements ResponseListener {
private Object cause;
// ...
@Override
public void messageReceived(String message, String status) {
// ...
if (!status.equals(MyConstants.COMPLD_MSG)) {
this.cause = status + " received for " + command.split(":")[0] + message;
this.failed = true;
}
doNotify();
}
@Override
public void exceptionCaught(Throwable cause) {
this.cause = cause;
this.failed = true;
doNotify();
}
public void waitForResponse(int cmdTimeout) throws IOException, InterruptedException {
// ...
if (failed)
throw cause instanceof String ? new IOException((String) cause) : new IOException((Throwable) cause);
}
}
答案 0 :(得分:0)
由于String
和Throwable
的共同超类不可作为IOException
的参数,因此您必须将其转换为其中一个,以便确定如何投射,你必须使用instanceof
。
答案 1 :(得分:0)
Class.cast和Class.isAssignableFrom方法可分别用作演员和instanceof
运算符的动态对应方。
答案 2 :(得分:0)
为什么原因变量总是 Throwable ? Throwable 似乎比String更适合表达失败。另外,它避免了你使用&#34;丑陋&#34; operator instanceof 。
public class Command implements ResponseListener {
private Throwable cause;
// ...
@Override
public void messageReceived(String message, String status) {
// ...
if (!status.equals(MyConstants.COMPLD_MSG)) {
this.cause = new Throwable(status + " received for " + command.split(":")[0] + message);
this.failed = true;
}
doNotify();
}
@Override
public void exceptionCaught(Throwable cause) {
this.cause = cause;
this.failed = true;
doNotify();
}
public void waitForResponse(int cmdTimeout) throws IOException, InterruptedException {
// ...
if (failed)
throw new IOException(cause);
}
}
以下讨论后更新:
public class Command implements ResponseListener {
private String cause;
// ...
@Override
public void messageReceived(String message, String status) {
// ...
if (!status.equals(MyConstants.COMPLD_MSG)) {
this.cause = status + " received for " + command.split(":")[0] + message;
this.failed = true;
}
doNotify();
}
@Override
public void exceptionCaught(Throwable cause) {
if(cause.getMessage().isEmpty()) {
this.cause = cause.toString();
}
else {
this.cause = cause.getMessage();
}
this.failed = true;
doNotify();
}
public void waitForResponse(int cmdTimeout) throws IOException, InterruptedException {
// ...
if (failed)
throw new IOException(cause);
}
}