考虑以下代码:
private static Context myContext;
public static Context getInstance() {
myContext = myContext == null ? new Context() : myContext;
return myContext;
}
像这样重构后,我的应用程序开始抛出NullPointers:
private static Context myContext;
public static Context getInstance() {
return myContext == null ? new Context() : myContext;
}
是否返回myContext并忽略'=='之后的所有内容? 有人可以解释一下吗?
编辑: 对此进行了一些研究,结果证明这是我的错误:似乎重构的代码未能将值赋给Context类字段。
很抱歉给您带来不便。
如果有人仍然感兴趣,这是工作代码段:
package pckg;
import org.junit.Test;
public class TernaryTest {
@Test
public void testOK(){
Context.getInstance().initialize();
Context.getInstance().setReport(new Report());
Context.getInstance().getReport();
}
@Test
public void testFail(){
Context.getInstanceRefactored().initialize();
Context.getInstanceRefactored().setReport(new Report());
Context.getInstanceRefactored().getReport();
}
}
class Context{
private static Context myContext;
private boolean isInitialized;
private Report report;
public static Context getInstance() {
myContext = myContext == null ? new Context() : myContext;
return myContext;
}
public static Context getInstanceRefactored() {
return myContext == null ? new Context() : myContext;
}
private void checkInitialized() {
if (!isInitialized) {
throw new IllegalStateException("Not initialized.");
}
}
public void initialize() {
if (isInitialized) {
throw new IllegalStateException("Not initialized.");
}
isInitialized = true;
}
public void setReport(Report report) {
this.report = report;
}
public Report getReport() {
checkInitialized();
return report;
}
}
class Report{}
答案 0 :(得分:1)
问题是你已经创建了myContext
的实例,但是在第二个版本中你从不为它赋值,而是创建一个匿名实例,它不绑定到更高范围的变量{{1 }}
myContext