Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

types

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?

like image 273
ollo Avatar asked Oct 26 '25 01:10

ollo


1 Answers

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.

like image 155
Peter Lawrey Avatar answered Oct 27 '25 14:10

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!