我敢肯定这是一个非常愚蠢的问题,但我仍然想知道,是否可以动态地强制使用全局变量cause
,换句话说,不使用instanceof
运算符?Java铸造(动态)
的原因的问题是,我觉得instanceof
运营商没有做任何事情大在这里,它只是铸造cause
静态,但在任何情况下,它是创造一个new IOException(cause)
因为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);
}
}
的instanceof是definetelly不是铸造。目前还不清楚你的问题是什么,看起来像XY问题。请尝试更具体。万一你在想什么XY问题是:http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem – zubergu
我想你可以使用一些阅读方法重载。这段代码实际上有点合理,因为不同的构造函数会根据'cause'的类型被调用。 –
“因为原因是Object类型”。它是或**需要**是?你需要首先做出区分吗? – zubergu