我的代码没有给出正确的结果,我开始排除故障并发现了一个奇怪的错误,有人可以向我解释一下吗。
如果我选择字段并执行此操作,结果会变为 result1 == false 且 result2 == true,为什么?
MyClass m1 = new MyClass();
MyClass m2 = new MyClass();
Field[] fieldsFirst = m1.getClass().getDeclaredFields();
Field[] fieldsSecond = m2.getClass().getDeclaredFields();
for (int i = 0; i < fieldsFirst.length; i++) {
Field first = fieldsFirst[i];
Field second = fieldsSecond[i];
first.setAccessible(true);
second.setAccessible(true);
if(first.get(m1) instanceof Boolean)
{
boolean b1 = (Boolean)first.get(m1);
boolean b2 = (Boolean)second.get(m2);
//Here are the results
boolean result1 = b1 != b2; // false
boolean result2 = (Boolean)first.get(m1) != (Boolean)second.get(m2); // true
}
如果我有:
public class MyClass {
private boolean myBoolean = true;
public boolean getMyBoolean()
{
return myBoolean;
}
public void setMyBoolean(booelan inBool)
{
myBoolean = inBool;
}
}
最佳答案
在
boolean result1 = b1 != b2; // false
您正在比较原始值,如 unboxing conversion 的 b1
和 b2
结果。从 boolean 值到 boolean 值。
在
boolean result2 = (Boolean)first.get(m1) != (Boolean)second.get(m2); // true
您正在比较引用文献。每个get()
的结果都引用不同的对象。因此,!=
比较为 true
。
关于java - java中Boolean和boolean的不同结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19497427/