“編不下去了!”~如何在泛型方法裏獲取T的類型?

我定義了一個hessian2反序列化的工具方法。爲了便於使用,使用了泛型。可是遇到了一個問題,其中調用的Hessian2Input#readObject的入參類型是Class實例。那麼,怎麼獲取泛型T的類型呢?

public static <T> T deserialize(byte[] bytes) throws IOException {
    try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes)) {
        Hessian2Input hessianInput = new Hessian2Input(byteArrayInputStream);
        try {
            hessianInput.setSerializerFactory(new SerializerFactory());
            Object object = hessianInput.readObject( 這裏如何在泛型方法裏獲取T的類型???????);
            log.debug("反序列化的對象=" + object.toString());
            return (T) object;
        } finally {
            hessianInput.close();
        }
    }
}

 

下面是我依賴的dubbo-2.7.3.jar中Hessian2Input#readObject的方法聲明。

/**
 * Reads an object from the input stream with an expected type.
 */
@Override
public Object readObject(Class cl)
        throws IOException {
    return readObject(cl, null, null);
}

 

 

揭曉答案↓↓↓

public static <T> T deserialize(byte[] bytes, Class<T> expectType) throws IOException {
    try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes)) {
        Hessian2Input hessianInput = new Hessian2Input(byteArrayInputStream);
        try {
            hessianInput.setSerializerFactory(new SerializerFactory());
            Object object = hessianInput.readObject(expectType);
            log.debug("反序列化的對象=" + object.toString());
            return expectType.cast(object);
        } finally {
            hessianInput.close();
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章