gpt4 book ai didi

java - 返回未知类型

转载 作者:行者123 更新时间:2023-11-29 07:26:35 25 4
gpt4 key购买 nike

目前我正在尝试编写一个返回未知对象类型的方法(序列化)。但是,我不断收到 java 要求我提供类型的错误 - 但显然,我不知道反序列化对象的具体类型是什么。

代码如下:

public static <?> T deSerialize(String path) throws IOException {//Line in question
try {
ObjectInputStream o = new ObjectInputStream(new FileInputStream(path));

return o.readObject();
}catch(Exception e) {
e.printStackTrace();
}
return null;

}

我知道我可以简单地返回类型 object,但我想知道如何使用泛型来做到这一点。

感谢您的帮助

最佳答案

readObject method in ObjectInputStream返回对正确类型的 Object 引用。

Read an object from the ObjectInputStream. The class of the object, the signature of the class, and the values of the non-transient and non-static fields of the class and all of its supertypes are read.

...

Java's safe casting should be used to get the desired type.

因此,您应该在调用该方法时让调用者将其转换为正确的类型。

// Non-generic method.
public static Object deSerialize(String path) throws IOException {

// ...
YourType foo = (YourType) deSerialize(path);

如果你必须让它成为通用的,那么你必须有一个类型见证,一个Class,它可以为你执行动态类型转换,这样类型就可以在编译时被编译器和运行时 Class.cast .仍然由调用者提供正确的 Class

public static <T> T deSerialize(String path, Class<T> clazz) throws IOException {
try {
ObjectInputStream o = new ObjectInputStream(new FileInputStream(path));

return clazz.cast(o.readObject());
}catch(Exception e) {
e.printStackTrace();
}
return null;
}

关于java - 返回未知类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51505023/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com