Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics void/Void types

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?

like image 845
Travis Webb Avatar asked Apr 06 '11 14:04

Travis Webb


People also ask

Can generic type be void?

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.

What is void type in Java?

The void keyword specifies that a method should not have a return value.

What is generic data type in Java?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.

What is generic type erasure?

Type erasure is a process in which compiler replaces a generic parameter with actual class or bridge method. In type erasure, compiler ensures that no extra classes are created and there is no runtime overhead.


1 Answers

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.

like image 70
ILMTitan Avatar answered Sep 20 '22 15:09

ILMTitan