In my code I (accidentially) wrote void.class
(not Void.class
) which was happily accepted by the compiler. Until now I thought that the primites are no real objects (not only void
, also talking about int
, etc... here), so they'd have no class.
I'm talking about all the "primitive classes". Every primitive type has a class denoted by <primitivetype>.class
, for example float.class
Class
" is referred to by such a "primitive class", e.g. void.class
?int.class.isInstance(2.3f)
?Void class is a placeholder that holds a reference to a class object if it represents a void keyword. It is an uninstantiable placeholder. Well, uninstantiable means that this class has a private constructor and no other constructor that we can access from outside.
The void keyword specifies that a method should not have a return value.
Void methods do some action (called a side-effect); they do not return any value; Type methods return some value; they do not do an action. Examples of void methods include output methods such as: outputInt, outputDouble, outputString, outputlnInt, etc.
what is difference between void and class??? void is a data type which means "No value" . we used void as a keyword to indicate that the function will not contain any return value. while class is a user defined type which contains data and functions in it.
void.class
is the object used in reflection to indicate that a method has void
return type. If you write method.getReturnType();
, this object may be returned.
int.class
can represent both arguments and return types.
You can write int.class.isInstance(...)
but it will always return false
, because the argument is an Object
.
No Class
object has an accessible constructor.
Both int.class.getConstructors()
and int.class.getDeclaredConstructors()
return an empty array. There are no constructors for primitive types.
The first obvious problem of Class
is that it also represents interfaces :)
Prior to java5, Class
is used to represent all java types, including primitive types. This is out of convenience, and it worked fine.
After generics was introduced, java types get a lot richer. java.lang.reflect.Type
was introduced to include all types. Unfortunately, it incorporates the old messy Class
, making an even bigger mess. The hierarchy of Type
just doesn't make sense.
Now, void
is not even a type! So Class
also include a non-type. That is out of convenience, as other answers have shown. Similarly, a wildcard is not a type either, yet WildcardType extends Type
!
Could void
have been designed as a type in the beginning? Why not. It's a primitive type of 0
bits, having exactly one value (aka, a unit type). I'm not sure how to feel if people write
void foo(void param){
param = bar(); // void bar(){...}
but at least I'll be happy if I could write
void foo(...){
return bar();
see also John Rose's comment
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With