在Java中,int.class是否等于Integer.class或Integer.TYPE? [英] Does int.class equal Integer.class or Integer.TYPE in Java?

查看:204
本文介绍了在Java中,int.class是否等于Integer.class或Integer.TYPE?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们想象一下使用反射来检索Field的声明类型.

Let's imagine one retrieves the declaring type of a Field using reflection.

以下哪项测试将正确指示正在处理int还是Integer?

Which of the following tests will correctly indicate whether one is dealing with an int or an Integer?

Field f = ...
Class<?> c = f.getDeclaringClass();
boolean isInteger;

isInteger = c.equals(Integer.class);
isInteger = c.equals(Integer.TYPE);
isInteger = c.equals(int.class);

isInteger = ( c == Integer.class);
isInteger = ( c == Integer.TYPE);
isInteger = ( c == int.class);

推荐答案

基于Field.getType()(而不是f.getDeclaringClass()),我得到以下信息:

Based on Field.getType() (instead of f.getDeclaringClass()), I get the following:

Type: java.lang.Integer

equals(Integer.class): true
equals(int.class)    : false
equals(Integer.TYPE) : false
== (Integer.class)   : true
== (int.class)       : false
== (Integer.TYPE)    : false

Type: int

equals(Integer.class): false
equals(int.class)    : true
equals(Integer.TYPE) : true
== (Integer.class)   : false
== (int.class)       : true
== (Integer.TYPE)    : true

Type: java.lang.Object

equals(Integer.class): false
equals(int.class)    : false
equals(Integer.TYPE) : false
== (Integer.class)   : false
== (int.class)       : false
== (Integer.TYPE)    : false

以下含义是正确的:

Integer.TYPE.equals(int.class)
Integer.TYPE == int.class

意味着如果我想确定我正在处理int还是Integer,我可以使用以下任何测试:

Meaning if I want to find out whether I am dealing with an int or an Integer, I can use any of the following tests:

isInteger = c.equals(Integer.class) || c.equals(Integer.TYPE);
isInteger = c.equals(Integer.class) || c.equals(int.class);
isInteger = (c == Integer.class) || (c == Integer.TYPE);
isInteger = (c == Integer.class) || (c == int.class );

我想念一个极端的情况吗?如果是,请发表评论.

Is there a corner case I am missing? If yes, please comment.

这篇关于在Java中,int.class是否等于Integer.class或Integer.TYPE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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