在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通过评估空对象上的类名演示了静态方法的使用。
热门推荐
10 鼠年元旦生日祝福语简短
11 女孩自己生日祝福语简短
12 感恩老婆礼物祝福语简短
13 学生老师离职祝福语简短
14 爱人出国祝福语简短英文
15 长辈生日祝福语简短大全
16 爱情红包祝福语简短英文
17 立春祝福语简短微信
18 送米的祝福语简短