为何ObjectInputStream.readObject()返回Object而非写入的具体类型?
Great question! Let’s unpack why this design choice makes sense for Java’s serialization system:
Flexibility first: support any serializable object
The whole point ofObjectOutputStreamis to let you write any object that implementsSerializable—not just yourCarclass. You could write aString, a customDogclass, or even a collection of mixed objects to the same stream. SincereadObject()has no way of knowing at compile time what type of object you wrote to the file, it has to return the most generic type that can hold any object:Object.Java’s static type system constraints
Java is a statically typed language, which means method return types are fixed at compile time. IfreadObject()returnedCar, how would it handle cases where you wrote a different serializable type? It couldn’t—this would break type safety and the system’s flexibility. ReturningObjectlets the developer (who knows what they wrote to the stream) cast to the correct type explicitly.Historical context
Serialization was added in Java 1.1, long before generics were introduced in Java 5. Even with modern generics, we can’t makereadObject()return a specific type because the actual type of the deserialized object is only known at runtime (when the byte stream is parsed). Generics are a compile-time feature, so they can’t bridge this gap.Explicit casting as a safety check
When you cast(Car) ois.readObject(), you’re telling the compiler: "I’m sure this object is a Car (or a subclass)." If you’re wrong (e.g., someone modified theobj.datfile to hold a different object), you’ll get aClassCastExceptionat runtime—this is a good thing, because it catches mismatches early instead of letting invalid types slip through silently.
For example, imagine you wrote code like this:
// Write a mix of objects oos.writeObject(new Car("yellow")); oos.writeObject("Hello World"); oos.writeObject(new Dog("buddy")); // Read them back Car car = (Car) ois.readObject(); // Works String str = (String) ois.readObject(); // Works Dog dog = (Dog) ois.readObject(); // Works
If readObject() returned a specific type, this kind of mixed-type serialization would be impossible.
内容的提问来源于stack exchange,提问作者Stefan

