英文:
Why does ObjectOutputStream.readObject() return object of type Object and not object of type I wrote it in?
问题
有关这个问题,我可以为您提供以下翻译:
假设我有一个名为 Car
的类:
class Car implements Serializable{
String color;
public Car(String color) {
this.color = color;
}
}
现在我想要将 Car
类的对象写入 ObjectStream
。代码如下所示:
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("obj.dat"));
oos.writeObject(new Car("yellow"));
然后当然我也想要读取这个对象!所以我需要这样做:
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("obj.dat"));
Car car = (Car) ois.readObject();
我的问题是:为什么方法 readObject()
返回的是 Object
而不是 Car
?难道我的 obj.dat
文件没有存储关于它所包含的对象的所有信息吗?毫无疑问它知道我要读取的对象的类型是 Car
。那么为什么它不直接返回 Car
,这样我就不必进行任何类型转换呢?
英文:
Say I have class Car
:
class Car implements Serializable{
String color;
public Car(String color) {
this.color = color;
}
}
Now I want to write object of class Car
into ObjectStream
. So it looks like this:
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("obj.dat"));
oos.writeObject(new Car("yellow"));
And then of course I would like to read object! So I would need to do this:
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("obj.dat"));
Car car = (Car)ois.readObject();
My question is following: Why does method readObject()
return Object
and not Car
? Doesn't my file obj.dat
store all information about objects it holds? So no doubt it knows object I want to read is of type Car
. So why it doesn't simply return Car
, so that I don't have to do any casting?
答案1
得分: 1
因为它无法知道文件/序列化数据中是什么类型的对象。
英文:
Because it has no way of knowing what type of object is in the file/serialized data.
答案2
得分: 1
它在这种情况下确实会返回一个 Car
。
但是编译器在编译时无法知道这一点,因为它取决于 obj.dat
中的数据。
因此编译器必须假设一般情况。它唯一确定的是 readObject()
将会返回某个 Object
。
如果你知道它始终是某个特定类型,你可以将其强制转换为更具体的类型,就像你之前所做的那样。
或者换个角度思考:如果你将一个 Car
对象和一个 Bike
对象依次序列化到同一个文件中,那么连续两次调用 readObject()
应该返回这两种类型。
现在,该方法的返回类型在静态上下文中已被定义,因此在 Java 类型系统中,第一次调用和第二次调用无法表现出不同的返回类型。
英文:
It does return a Car
in this case.
But the compiler can't know that at compile time, because it depends on the data in obj.dat
.
So the compiler has to assume the general case. The only thing it knows for sure is that readObject()
will return some Object
.
You can cast it to a more specific type if you know it will always be that, just as you did.
Or think about it the other way around: if you serialized a Car
object and a Bike
object after each other in the same file, then calling readObject()
twice should return those two types.
Now the return type of that method is defined statically, so there's no way in the Java type system for the first call to indicate a different return type than the second call.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论