Why is java.lang.Void not Serializable?
OK, in response to your example, no if you changed the method to void
it would not work, as the method has to have a return type (even if Java now allows covariant return types in overridden methods). The discussion of void
confuses the issue.
What you want to do is declare a type parameter as a "will just return null." Void is generally a good choice for that, but for Void to work, the return type has to be Object. Void can't implement every interface in the API just because someone might want to use it to indicate a null return on a type parameter.
There are three ways to look at your problem:
- Serializable is an overly restrictive type declaration. You should really be using Object. Do you really need it to be Serializable?
- You can just declare the type parameter as Serializable, and in practice return null. This dosn't fully indicate that you are returning null every time, but it may be enough.
- You can declare your own class called Null which implements Serializable, perhaps as a static nested class of the Root interface, and use that as the type parameter in this case. You will find making your own Null object is not that uncommon, even in the standard JDK there is (a private) one.
The javadoc is clear:
The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword
Because you can not use it, it does not need to be Serializable (except reflection stuff).
And for the second question: void != Void (if you are think about != in a not java expression)
Yes void
is a keyword and Void
a class.
I will put it here as comminity-wiki
Thou can (de)serialize java.lang.Void
b/c you can initialize it with null only. Java doesn't care if a class implements java.io.Serializable
if it's null
.
Result of the code
t1.VoidOut@19821f t1.VoidOut@c17164
public class VoidOut implements java.io.Serializable{
int x=1;
Void v = null;
public static void main(String[] args) throws Throwable{
VoidOut v = new VoidOut();
System.out.println(v);
ByteArrayOutputStream b =new ByteArrayOutputStream(256);
ObjectOutputStream o = new ObjectOutputStream(b);
o.writeObject(v);
o.close();
ObjectInputStream in =new ObjectInputStream(new ByteArrayInputStream(b.toByteArray()));
System.out.println(in.readObject());
}
}