为什么原始类型具有“类”?它是如何用于使用的? [英] Why do primitive types have a "Class" and how is it intended for using?

查看:196
本文介绍了为什么原始类型具有“类”?它是如何用于使用的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谈到Java(7),你可以获得这样一个基本类的类:

Talking about Java (7) you can get a class for a primitive type like this:

Class classOfInt = int.class

对于每一个,你将获得一个名为基元类型的类:

For each one you'll get a "class" named as the primitive type:

int.class    --> int
byte.class   --> byte
double.class --> double
...

但是你无法创建那些实例:

However you can't create an instance of those:

char.class.newInstance(); // throws 'InstantiationException'

它们的类似乎没有映射到相应的包装类(整数字节等。)

It seems that their classes are not mapped to corresponding wrapper classes (Integer, Byte, etc.).

为什么呢?他们有类,它们是如何使用的以及它们是如何实现的?

So why do they have "classes", how are they used and how are they implemented?

推荐答案

它们用于反射。

Method round = Math.class.getMethod("round", double.class);
System.out.println(Arrays.toString(round.getParameterTypes()));
System.out.println(round.getReturnType() == long.class);

Method exit = System.class.getMethod("exit", int.class);
System.out.println(Arrays.toString(exit.getParameterTypes()));
System.out.println(exit.getReturnType() == void.class);

打印

[double]
true
[int]
true




它们是如何实现的?

how are they implemented?

它们内置于JVM,没有类文件定义它们。

They are builtin to the JVM, there is no class file to define them.

这篇关于为什么原始类型具有“类”?它是如何用于使用的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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