buguge - Keep it simple,stupid

知识就是力量,但更重要的,是运用知识的能力why buguge?

导航

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

我定义了一个hessian2反序列化的工具方法。为了便于使用,使用了泛型。可是遇到了一个问题,其中调用的Hessian2Input#readObject的入参类型是Class实例。那么,怎么获取泛型T的类型呢?

    /**
     * hessian2反序列化,得到反序列对象
     * @param bytes 序列化时生成的字节数组
     * @param <T>
     * @return
     * @throws IOException
     */
    public static <T> T deserialize(byte[] bytes) throws IOException {
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes)) {
            Hessian2Serialization hessian2Serialization = new Hessian2Serialization();
            try {
                ObjectInput objectInput = hessian2Serialization.deserialize(null, byteArrayInputStream);
                T object = objectInput.readObject( 这里如何在泛型方法里获取T的类型??????? );
                log.debug("反序列化的对象=" + object.toString());
                return object;
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

 

下面是我依赖的org.apache.dubbo:dubbo:2.7.3.jar中org.apache.dubbo.common.serialize.ObjectInput#readObject的方法声明。

    /**
     * read object
     *
     * @param cls object class
     * @return object
     * @throws IOException if an I/O error occurs
     * @throws ClassNotFoundException if an ClassNotFoundException occurs
     */
    <T> T readObject(Class<T> cls) throws IOException, ClassNotFoundException;    

 

 

揭晓答案↓↓↓

    /**
     * hessian2反序列化,得到反序列对象
     *
     * @param bytes       序列化时生成的字节数组
     * @param <T>
     * @param objectClass 泛型T的class
     * @return
     * @throws IOException
     */
    public static <T> T deserialize(byte[] bytes, Class<T> objectClass) throws IOException {
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes)) {
            Hessian2Serialization hessian2Serialization = new Hessian2Serialization();
            try {
                ObjectInput objectInput = hessian2Serialization.deserialize(null, byteArrayInputStream);
                T object = objectInput.readObject(objectClass);
                log.debug("反序列化的对象=" + object.toString());
                return object;
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

 

posted on 2023-05-30 11:42  buguge  阅读(47)  评论(0编辑  收藏  举报