Skip to content

Instantly share code, notes, and snippets.

@xuwei-k
Forked from rabitarochan/classmanifesttest.scala
Created August 31, 2012 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xuwei-k/3554585 to your computer and use it in GitHub Desktop.
Save xuwei-k/3554585 to your computer and use it in GitHub Desktop.
ScalaのClassManifestについてハマった
// コンストラクタをプライベートにし、コンパニオンオブジェクト経由でのみ生成させる。
class ClassName[A] private (val clazz: Class[A]) {
// toString で、引数に指定されたクラスの名称を返す。
override def toString(): String = {
clazz.getName
}
}
object ClassName {
// Classを直接渡して生成する。
def create[A](clazz: Class[A]): ClassName[A] = new ClassName(clazz)
// 型パラメータの情報を ClassManifest から取得して生成する。
def create[A]()(implicit m: ClassManifest[A]) = new ClassName(m.erasure)
}
object Main extends App {
val c1 = ClassName.create(classOf[String])
val n1 = println(c1.toString) // => java.lang.String
val c2 = ClassName.create[Int]
val n2 = println(c2.toString) // => int
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment