How can we use .class on primitive types?
Asked Answered
Z

3

14

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?

Zelikow answered 25/9, 2013 at 11:57 Comment(1)
I think this is one of antipatterns in java.Attired
T
15

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);
Trumaine answered 25/9, 2013 at 12:2 Comment(0)
P
0

Found another application for e.g. int.class. Consider to mock the method

class MyClass {
    int myMethod(final int arg) {}
}

To mock it with Mockito you may use:

    when(myClass.myMethod(any(int.class)).thenReturn(1);

I was surprised myself that this actually works and it is more clearer than simply

    when(myClass.myMethod(any()).thenReturn(1);
Patellate answered 21/5, 2021 at 15:58 Comment(0)
D
-2

primitive is not a class. These are some reserved types in Java.

When you say Integer, it's a class in java.lang package such as :

class Integer{ ............ }

so for any class you can use .class, Not applicable for primitives. BTW, why do you need this? What is the use?

Detwiler answered 25/9, 2013 at 12:1 Comment(1)
Actually you can do primitive.class (for example int.class). There are use cases for this as @Trumaine said.Calandracalandria

© 2022 - 2024 — McMap. All rights reserved.