Kengo's blog

Technical articles about original projects, JVM, Static Analysis and TypeScript.

メモ:Class・Method・ClassLoaderのソースコードを読む

JVM寄りすぎるためにJavaのコードを追うだけでは得られる情報は限られてしまうようですが、代わりに新しいメソッドや修飾子に関する情報を得ることができました。

  • native修飾子を利用することで、他言語で実装されたメソッドを呼べる。
  • Methodクラスを利用することで、柔軟なメソッド呼び出しが可能。ただしスローされる例外も多い。
	// Integer#toStringをMethodクラスを利用して呼び出す

	Integer integer = new Integer(100);
	try {
		Method toString = Integer.class.getMethod("toString", null);
		System.out.println("Integer(100).toString = " + toString.invoke(integer, null));
		// => Integer(100).toString = 100
	} catch (Exception e) {
		// コード短縮のためExceptionとしてcatch
		e.printStackTrace();
	}
  • ClassLoaderで利用されているReflection#getCallerClass(int)は、呼び出し元のクラスを取得するメソッド。ただし利用は非推奨*1
	Class caller = null;
	for (int i = 0; (caller = sun.reflect.Reflection.getCallerClass(i)) != null; ++i) {
		System.out.println(caller.getName());
	}

*1:http://d.hatena.ne.jp/unageanu/20070522 を参照