“这代码编不下去了!”~如何在泛型方法里获取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; }
当看到一些不好的代码时,会发现我还算优秀;当看到优秀的代码时,也才意识到持续学习的重要!--buguge
本文来自博客园,转载请注明原文链接:https://www.cnblogs.com/buguge/p/17442833.html