多年来我一直在编写 Java swing GUI 代码,但以下语法让我感到困惑。我说的是下面方法的“< R extends IPCMessage > R”部分。我在另一位工程师编写的库中找到了这个,但我不知道如何使用它。
我非常熟悉泛型的其他用途,但我不知道这个。
谁能解释一下发生了什么以及我该如何使用它?
谢谢。
/**
* Sends the specified IPC message to the process the IPC instance is
* connected to
*
* @param msg
* the IPC message to send
* @return IPCMessageRx for the received response message if want_resp is
* true null if want_resp is true and no response was received
* within the timeout null if want_resp is false
* @throws InvalidCastException if the return type doesn't match the actual
* type of the response.
*/
@SuppressWarnings("unchecked")
public <R extends IPCMessage> R sendAndGetResponse(IPCMessage msg)
{
logger.logTrace("IPClient::sendAndGetResponse: entered, msg = \"" + msg.toString() + "\"");
// keep track of whether the message sent
boolean msg_sent = send(msg);
// if the message sent and a response is wanted, try to get one from the
// received message buffer
IPCMessage back = null;
if (msg_sent == true)
{
back = receive(msg.getSequenceNumber());
}
if (back == null)
{
logger.logDebug("IPClient::send: exiting, back = null");
}
else
{
logger.logTrace("IPCClient::send: exiting, back != null");
}
return (R)back;
}
最佳答案
对我来说,以这种方式使用泛型是没有用的。最重要的是,永远不会从方法中抛出 InvalidCastException。
最好使用下面的代码,让调用者自己做转换:
IPCMessage sendAndGetResponse(IPCMessage msg) {...}
关于java - 我该如何使用它? public <R extends IPCMessage> R sendAndGetResponse(IPCMessage 消息),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9915858/