在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通过评估空对象上的类名演示了静态方法的使用。
热门推荐
7 足球队祝福语简短
10 幼儿狗年祝福语大全简短
11 顾客简短祝福语大全集
12 别人过大寿祝福语简短
13 孩子16岁祝福语简短
14 爱情祝福语大全 简短实际
15 女神节日简短祝福语大全
16 送外卖祝福语大全简短
17 祝老婆生日祝福语简短
18 新年祝福语和语句简短