java - 我该如何使用它? public <R extends IPCMessage> R sendAndGetResponse(IPCMessage 消息)

标签 java generics

多年来我一直在编写 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/

相关文章:

java - 为什么不在 LinkedList 中定义 ListIterator 的静态类?

python - django ListView 指定可用于类内所有方法的变量

java - 是否可以在反射的帮助下重建通用返回类型 - Java?

java - 无法导入内包中的 Protobuf 消息

java - 交换和旋转二维数组

Java 泛型 - 删除机制

java - 在 Android 上将 Java 8 OffsetDateTime 转换为本地化字符串的最佳/推荐方法

c# - 用泛型重构

java - 类型参数导致错误

java - 将通用 java 类型保存/加载到 postgresql 数据库列