为什么Groovy中的整数比较返回false?

时间:2016-06-06 17:25:54

标签: groovy integer

由于以下行为,我在项目中发现了一个错误:

int a = 1
Integer b = 2
assert a.class == b.class // ok, they are the same class
assert Integer.class != int.class // what?! they are different!

有人知道为什么以及如何处理这个问题?

我正在使用Groovy 2.3.7 此致

1 个答案:

答案 0 :(得分:0)

使用@alfasin链接和@Nathan评论,我发现a正在向Integer进行自动转换(自动装箱)。

这就是a.class == b.classInteger.class != int.class

的原因

在我的具体问题中,我使用反射来使用clazz.getDeclaredFields()来获取字段的类。类中的值是int,但我必须比较的值是Integer。

要解决这个问题,我正在使用下面的帮助器类,它将int转换为Integer:

import org.apache.commons.lang.ClassUtils
ClassUtils.primitiveToWrapper(int.class) == Integer.class

谢谢大家!