我们如何在原始类型上使用.class? [英] How can we use .class on primitive types?

查看:40
本文介绍了我们如何在原始类型上使用.class?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们说

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?

推荐答案

该文档记录在

原始Java类型(布尔,字节,字符,short,int,long,float和double)以及关键字void也表示为Class对象.

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.

想象一个方法:

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

您可以通过以下方式访问它:

You can access it with:

MyClass.class.getDeclaredMethod("m", int.class);

这篇关于我们如何在原始类型上使用.class?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆