Java generics void/Void types
JavaVoidReturn TypeJava Problem Overview
I am implementing a ResponseHandler
for the apache HttpClient package, like so:
new ResponseHandler<int>() {
public int handleResponse(...) {
// ... code ...
return 0;
}
}
but I'd like for the handleResponse
function to return nothing, i.e. void
. Is this possible? The following does not compile, since void
is not a valid Java type:
new ResponseHandler<void>() {
public void handleResponse(...) {
// ... code ...
}
}
I suppose I could replace void
with Void
to return a Void
object, but that's not really what I want. Question: is it possible to organize this callback situation in such a way that I can return void
from handleResponse
?
Java Solutions
Solution 1 - Java
The Void
type was created for this exact situation: to create a method with a generic return type where a subtype can be "void". Void
was designed in such a way that no objects of that type can possibly be created. Thus a method of type Void
will always return null
(or complete abnormally), which is as close to nothing as you are going to get. You do have to put return null
in the method, but this should only be a minor inconvenience.
In short: Do use Void
.
Solution 2 - Java
Generics only handles object classes. void and primitive types are not supported by Generics and you cannot use these as a parameterized type. You have to use Void instead.
Can you say why you don't want to use Void
?
Solution 3 - Java
When you need to return java.lang.Void
, just return null
.
Solution 4 - Java
You can't have primitives in generics so that int
is actually an Integer
. The object Void
is analogous with the keyword void
for generics.
Solution 5 - Java
Alas it's not possible. You can set the code to return Void
as you say, however you can never instanciate a Void
so you can't actually write a function which conforms to this specification.
Think of it as: The generic function says "this function returns something, of type X", and you can specify X but you can't change the sentence to "this function returns nothing". (I'm not sure if I agree with these semantics, but that's the way they are.)
In this case, what I always do, is just make the function return type Object
, and in fact always return null
.
Solution 6 - Java
This java.lang.Void implementation in Java kind of speaks for itself. Also, I wrote an article that ties this into generics. It took a bit of thought before I started understanding this: http://www.siteconsortium.com/h/D00006.php. Notice TYPE = Class.getPrimitiveClass("void");
package java.lang;
public final class Void {
public static final Class<Void> TYPE = Class.getPrimitiveClass("void");
private Void() {}
}