Skip to content
Advertisement

How can we use .class on primitive types?

When we say

JavaScript

it prints

class java.lang.Integer

which makes sense because java.lang.Integer is a class. So we can have a corresponding Class object.

But when I do

JavaScript

it prints int which I felt is kind of ambiguous as .class returns an object of type Class and int is not a class (but a primitive type).

What is the motive behind allowing .class operation on primitive types when there is no such class (primitiveType.class.getName()) present?

Also if you see toString() method of class Class

JavaScript

As primitive types are not classes or interfaces it simply print the name (int for int). So why allow creating Class objects of a class which is not present?

Advertisement

Answer

It is documented in the javadoc:

The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.

It is particularly useful when you want to call a method that expects primitive arguments via reflection.

Imagine a method:

JavaScript

You can access it with:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement