在Java中使用null调用方法
当在空引用上调用某个方法时,它会抛出NullPointerException,但是对于静态方法,我们可以使用强制转换表达式来实现。请参阅下面的示例-
示例
public class Tester {
public static void display(){
System.out.println("display");
}
private void print() {
System.out.println("print");
}
public static void main(String[] args) {
//Scenario 1:
//Calling a method on null reference
//causes NullPointerException
try {
Tester test = null; test.print();
}catch(Exception e) {
System.out.println(e.getMessage());
}
//Scenario 2:
//Static method can be invoked
//on a null object by using the casting expression
((Tester)null).display();
}
}输出结果
null display
笔记
方案1演示了导致NullPointerException的代码。
方案2通过评估空对象上的类名演示了静态方法的使用。
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短