Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is java.lang.Void not Serializable?

Tags:

java

void

It is possible to serialize the primitive 'void' per default, why does not the object 'Void' extend Serializable?

Added example:

The RootImplementation will have a compilation error saying "Void is not within its bound" since it does not extend Serializable. Though would 'someMethod' be declared with 'void' it would be no problem.

public interface Root<R extends Serializable> extends Serializable {
  R someMethod();
}

public class RootImplementation implements Root<Void> {
  public Void someMethod() {
    return null;
  }
}
like image 557
Tomas F Avatar asked Feb 11 '11 15:02

Tomas F


People also ask

Is Java Lang object serializable?

Another important point about java. lang. Object not implementing the Serializable interface is that any class you create that extends only Object (and no other serializable classes) is not serializable unless you implement the interface yourself (as done with the previous example).

Which Java classes are not serializable?

io. Serializable interface. This is only a marker interface which tells the Java platform that the object is serializable. Certain system-level classes such as Thread , OutputStream and its subclasses, and Socket are not serializable.

Why optional is not serializable?

There is a good reason to not allow Optional to implement Serializable, it promotes a bad way to use Optional [...] Optional is nice from the API point of view, but not if you store it in a field. If it's not something that should be stored in field, there is no point to make it serializable.


1 Answers

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:

  1. Serializable is an overly restrictive type declaration. You should really be using Object. Do you really need it to be Serializable?
  2. 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.
  3. 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.
like image 182
Yishai Avatar answered Sep 18 '22 23:09

Yishai