我们如何在原始类型上使用.class? [英] How can we use .class on primitive types?
问题描述
当我们说
Class c = Integer.class;
System.out.println(c);
它打印
类java.lang.Integer
之所以有意义,是因为 java.lang.Integer
是一个类.因此我们可以有一个对应的 Class
对象.
which makes sense because java.lang.Integer
is a class. So we can have a corresponding Class
object.
但是当我这样做
Class c1 = int.class;
System.out.println(c1);
它打印出 int
,我觉得这有点模棱两可,因为 .class
返回的对象类型为 Class
和 int
不是类(而是原始类型).
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).
在不存在这样的类( primitiveType.class.getName()
)的情况下,允许对原始类型进行.class操作的动机是什么?
What is the motive behind allowing .class operation on primitive types when there is no such class (primitiveType.class.getName()
) present?
此外,如果您看到类 Class
public String toString() {
return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
+ getName();
}
由于基本类型不是类或接口,因此仅打印名称(对于 int
,则为 int
.).那么为什么要允许创建不存在的类的 Class
对象呢?
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?