基本类型类的用途/目的是什么? [英] What is the use/purpose of primitive type classes?

查看:159
本文介绍了基本类型类的用途/目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近了解到,原始图片有 Class 表示形式类型在JVM中。例如, int.class double.class ,甚至一个 void.class

I recently learned that there are Class representations for the primitive types in the JVM. For example, int.class, double.class, and even a void.class.

我不明白的是为什么他们似乎不起任何功能作用。使用反射,我搜索的类,他们没有构造函数,没有方法,没有字段。对于所有的意图和目的,他们似乎空和无用。原始类型变量不是它们各自类的实例,如下面返回false所示:

What I don't understand is why these are there. They don't seem to serve any functional role. Using reflection, I searched through the classes, and they have no constructors, no methods, and no fields. For all intents and purposes, they seem empty and useless. The primitive type variables are not even instances of their respective classes, as indicated by the following returning false:

int a = 3;
int.class.isInstance(a);

那么为什么它们存在呢?他们必须服务于一些目的,也许为编译器或某事,但无论它是完全超出我。在 int.class lang / Integer.html#TYPE>整数API (对于每个基本类型及其相应的包装器对象也是如此)。

So why do they exist? They must serve some purpose, maybe for the compiler or something, but whatever it is is completely beyond me. There is even an explicit reference to int.class in the Integer API (and likewise for each primitive type and its respective wrapper Object). I haven't been able to find any reference to their existence, much less their use, in the JLS.

推荐答案


我不明白为什么会出现这种情况。

What I don't understand is why these are there.

请考虑以下情况:

public int foo() {
    return 0;
}

...

Method method = someClass.getDeclaredMethod("foo");
Class<?> clazz = method.getReturnType();

没有 $ c> int ,上面的返回是什么?它不应该返回 Integer.class ,因为它们不是同样的东西。 (试想区分重载的方法,一个用 int ,一个用 Integer 参数。)

Without a Class representation of int, what would the above return? It shouldn't return Integer.class as they're not the same thing. (Imagine trying to distinguish between methods which were overloaded, one with an int and one with an Integer parameter.)

我使用这些类之前提供参数的默认值,当通过反射调用。基于参数类型,我对任何引用类型使用了 null ,对于每个基本类型,使用了一些(包装,明显)原始值。

I've used these classes before to provide default values for arguments when calling them via reflection. Based on the parameter type, I've used null for any reference type, and some (boxed, obviously) primitive value for each of the primitive types.

这篇关于基本类型类的用途/目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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