当我写这样的java代码时:
Map<String, Long> map = new HashMap<>()
Long number =null;
if(map == null)
number = (long) 0;
else
number = map.get("non-existent key");
Run Code Online (Sandbox Code Playgroud)
应用程序按预期运行但是当我这样做时:
Map<String, Long> map = new HashMap<>();
Long number= (map == null) ? (long)0 : map.get("non-existent key");
Run Code Online (Sandbox Code Playgroud)
我在第二行得到一个NullPointerException.调试指针从第二行跳转到java.lang.Thread类中的this方法:
/**
* Dispatch an uncaught exception to the handler. This method is
* intended to be called only by the JVM.
*/
private void dispatchUncaughtException(Throwable e) {
getUncaughtExceptionHandler().uncaughtException(this, e);
}
Run Code Online (Sandbox Code Playgroud)
这里发生了什么?这两个代码路径都完全等价不是吗?
编辑
我使用的是Java 1.7 U25
我已经看到了通过引用类对象并使用一个create方法来实现对象创建工厂的地方:class.newInstance()它使用反射,与直接调用默认构造函数相比可能效率不高.
如果java支持类似的东西return new this();,我可以在父类中实现它,这将作为工厂方法(如果没有这样的构造函数,将抛出异常class.newInstance()).
为什么不支持这样的东西?
PS:我在stackOverflow中的第一个问题:)