I’ve been writing Java swing GUI code for several years but the following syntax stumps me. I’m talking about the ” < R extends IPCMessage > R” portion of the method below. I found this in a library another engineer wrote and I have no idea how to use it.
I’m very familiar with the other uses of generics but this one I don’t know.
Can someone explain what is going on and how I can use it?
Thank you.
/**
* 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;
}
Well, basically the method lets you choose its return type. But because this is no safe way to use generics, a runtime exception may occur (as documented by the method), so one should always try to avoid such situations. However, sometimes it is very hard to accomplish and sometimes it is impossible at all.
Anyway, I think that this engineer was no Java expert, as he does not even adhere to the naming conventions (camel case variable names).
But now, here is what you can do with this method: Say, you have your own
IPCMessageclass:Then, you need to know that the response of the message you want to send has the type
MyMessage(which could be the tough part, but I can’t tell this without knowing the rest of the code) and may call: