Search code examples
javatypes

Why do primitive types have a "Class" and how is it intended to be used?


Talking about Java (7) you can get a class for a primitive type like this:

Class classOfInt = int.class

For each one you'll get a "class" named as the primitive type:

int.class    --> int
byte.class   --> byte
double.class --> double
...

However you can't create an instance of those:

char.class.newInstance(); // throws 'InstantiationException'

It seems that their classes are not mapped to corresponding wrapper classes (Integer, Byte, etc.).

So why do they have "classes", how are they used and how are they implemented?


Solution

  • They are used in reflection.

    Method round = Math.class.getMethod("round", double.class);
    System.out.println(Arrays.toString(round.getParameterTypes()));
    System.out.println(round.getReturnType() == long.class);
    
    Method exit = System.class.getMethod("exit", int.class);
    System.out.println(Arrays.toString(exit.getParameterTypes()));
    System.out.println(exit.getReturnType() == void.class);
    

    prints

    [double]
    true
    [int]
    true
    

    how are they implemented?

    They are builtin to the JVM, there is no class file to define them.