4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

レシーバがnullでもNullPointerExceptionにならない時もある

Posted at

最近気づいたさしずめどうでも良い話ですが、
例えば、下記のような挑発的な書き方でもエラーにならないことがあることに気づきました。

	((Foo) null).sayHello();

で、Foo.sayHelloってなんぞやと言うと、

public class Foo {
	public static void main(String[] args) {
		((Foo) null).sayHello();
	}
	
	public static void sayHello() {
		System.out.println("hello");
	}
}

staticだとレシーバがnullでもOKみたいです(正直なところstaticメソッドにレシーバが付けられるのはJavaの不思議仕様)

おまけ

staticメソッドには仮想関数のような、実行時の型を解決する機能は無いみたいです。

public class Foo {
	public static void main(String[] args) {
		((Hello) new A()).sayHello();
		// -> hello
	}
}

class Hello {
	public static void sayHello() {
		System.out.println("hello");
	}
}
class A extends Hello {
	public static void sayHello() {
		System.out.println("hello, I am A.");
	}
}

なんならリフレクションを使って関係無い型をレシーバに渡しても何も言われません。

public class Foo {
	public static void main(String[] args) throws Exception {
		Class<Hello> klass = Hello.class;
		Method method = klass.getMethod("sayHello");
		method.invoke(100);
		// (new Integer().sayHello)
	}
}

class Hello {
	public static void sayHello() {
		System.out.println("hello");
	}
}
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?