getClass
上
Here is the ticketとlinked forum discussion:
また、キャストを使用することができます。
Here is the duplicate ticketgetClass
が固定されている。 5.getClass
もキャスト:
/** Return the class object representing an unboxed value type,
* e.g. classOf[int], not classOf[java.lang.Integer]. The compiler
* rewrites expressions like 5.getClass to come here.
*/
def anyValClass[T <: AnyVal : ClassTag](value: T): jClass[T] =
classTag[T].runtimeClass.asInstanceOf[jClass[T]]
制限は、私たちの素朴な期待も満たされていないされているClassTag
とthis question about pattern matching、を彷彿とさせます。
Class[A]
への抵抗は、Scalaタイプとプラットフォーム間のインピーダンスの不一致を表しますか?
クラスタイプを指定すると、すべて実際に行うことができるのはnewInstance
です。しかし、コンストラクター・ミラーを使用したリフレクション・コールでは、自分のタイプを戻すことはできません。
scala> res24 reflectConstructor res25.asMethod
res27: reflect.runtime.universe.MethodMirror = constructor mirror for Bar.<init>(): Bar (bound to null)
scala> res27()
res28: Any = [email protected]
scala> bar.getClass.newInstance
res29: Bar = [email protected]
scala> classOf[Bar].newInstance
res30: Bar = [email protected]
これは公平ではないようです。
2008年のこのメールスレッドでは、Scalaでのキャスト数が少なくなると予想しています。
ところで、それは私が、コードのコメントを信じなかったが、ということはありません。
scala> 5.getClass
res38: Class[Int] = int
scala> :javap -
Size 1285 bytes
MD5 checksum a30a28543087238b563fb1983d7d139b
Compiled from "<console>"
[省略]
9: getstatic #27 // Field scala/runtime/ScalaRunTime$.MODULE$:Lscala/runtime/ScalaRunTime$;
12: iconst_5
13: invokestatic #33 // Method scala/runtime/BoxesRunTime.boxToInteger:(I)Ljava/lang/Integer;
16: getstatic #38 // Field scala/reflect/ClassTag$.MODULE$:Lscala/reflect/ClassTag$;
19: invokevirtual #42 // Method scala/reflect/ClassTag$.Int:()Lscala/reflect/ClassTag;
22: invokevirtual #46 // Method scala/runtime/ScalaRunTime$.anyValClass:(Ljava/lang/Object;Lscala/reflect/ClassTag;)Ljava/lang/Class;
25: putfield #18 // Field res38:Ljava/lang/Class;
28: return
Javaのリフレクションを使用するときは、鋳物を恐れてはなりません。 'asInstanceOf [Class [T]]'を実行するだけです。 –