java如何使用它?public<R extends IPCMessage>R sendAndGetResponse(IPCMessage msg)
我已经编写JavaSwingGUI代码好几年了,但是下面的语法让我感到困惑。我在谈论下面方法的“<;R>;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;
}
# 1 楼答案
这是一种通用方法。基本上,该方法的签名表示,只要它扩展了IPCMessage,它将返回您希望它返回的任何类型的对象
# 2 楼答案
对我来说,这样使用泛型是没有用的。最重要的是,InvalidCastException永远不会从方法中抛出
最好使用以下代码,让调用者自己执行强制转换:
# 3 楼答案
基本上,这个方法允许你选择它的返回类型。但是,由于这不是使用泛型的安全方法,因此可能会发生运行时异常(如该方法所记录的),因此应该始终尝试避免此类情况。然而,有时很难做到,有时根本不可能做到
无论如何,我认为这位工程师不是Java专家,因为他甚至不遵守命名约定(驼峰大小写变量名)
但是现在,你可以用这个方法做些什么:比如说,你有自己的
IPCMessage
类:然后,您需要知道您想要发送的消息的响应类型为
MyMessage
(这可能是最困难的部分,但在不了解其余代码的情况下,我无法说出这一点),并且可能会调用:# 4 楼答案
这种方法在我看来不太好,因为它不能保证最后一次投法是正确的。因此,我将删除SuppressWarning注释
这些方法可用于以下方面:
但是您必须确保在方法之前传递的类型是您将实际接收的类型。我觉得这不安全。将类型作为方法的参数传递,以便安全地检查返回的类型,这将更有意义