“编不下去了!”~如何在泛型方法里获取T的类型?

发布时间 2023-05-30 11:55:35作者: buguge

我定义了一个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();
        }
    }
}