我对为什么这段代码在理想情况下必须抛出空指针异常时起作用的概念感到惊讶
public class Test {
public static String foo(){
System.out.println("Test foo called");
return "";
}
public static void main(String args[]){
Test obj = null;
System.out.println(obj.foo());
}
}
最佳答案
当调用静态方法时,类型引用与实例相关,因此 obj.foo() 和 Test.foo() 被解析为相同的东西。
最佳实践:应静态访问静态成员
While it is possible to access static members from a class instance, it's bad form, and considered by most to be misleading because it implies to the readers of your code that there's an instance of the member per class instance.
https://sonarqube.com/coding_rules#rule_key=squid%3AS2209
建议编码如下:
public static void main(String args[]) {
Test obj = null;
// ....
System.out.println(Test.foo());
}
关于java - 为什么类中的静态方法在其对象为空时不会给出空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43789332/