WorldSEnder
WorldSEnder

Reputation: 5044

What does `void.class` denote?

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

Upvotes: 5

Views: 1274

Answers (3)

ZhongYu
ZhongYu

Reputation: 19682

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

Upvotes: 2

Paul Boddington
Paul Boddington

Reputation: 37645

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.

Upvotes: 6

Kumar Abhinav
Kumar Abhinav

Reputation: 6675

Void is a placeholder for return type void used in Reflections.

Example:- void.class is the return type for the methods returning void as in main method below:-

import java.lang.reflect.Method;

public class A{
    public static void main(String[] args) throws NoSuchMethodException, SecurityException{

    Method mh = A.class.getMethod("main",String[].class);
    System.out.println(mh.getReturnType() == void.class);

    }
}

Upvotes: 0

Related Questions