Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we use .class on primitive types?

When we say

Class c = Integer.class;
System.out.println(c);

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

Class c1 = int.class;
System.out.println(c1);

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

public String toString() {
    return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
        + getName();
}

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?

like image 208
Aniket Thakur Avatar asked Sep 25 '13 11:09

Aniket Thakur


People also ask

Can a class be used for a primitive type?

A Wrapper class in Java is used to convert a primitive data type to an object and object to a primitive type. Even the primitive data types are used for storing primary data types, data structures such as Array Lists and Vectors store objects.

Can class be used for primitive type in Java?

So a primitive wrapper class is a wrapper class that encapsulates, hides or wraps data types from the eight primitive data types, so that these can be used to create instantiated objects with methods in another class or in other classes. The primitive wrapper classes are found in the Java API.

Is class primitive data type?

Other than the primitive data types, all data types are classes. In other words, data is either primitive data or object data. Every object in Java is an instance of a class. A class definition has to exist first before an object can be constructed.


1 Answers

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:

class MyClass {
    void m(int i) {}
}

You can access it with:

MyClass.class.getDeclaredMethod("m", int.class);
like image 83
assylias Avatar answered Oct 07 '22 13:10

assylias