Skip to content

Instantly share code, notes, and snippets.

@seraphr
Created February 17, 2014 22:25
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 seraphr/9060448 to your computer and use it in GitHub Desktop.
Save seraphr/9060448 to your computer and use it in GitHub Desktop.
scalaのリフレクションで、コンストラクタの有無を確認するコード
import scala.reflect.runtime.universe._
class TypeCheck[T: WeakTypeTag]{
val mClassType = implicitly[WeakTypeTag[T]].tpe
val mConstructors = mClassType.members.filter(_.isMethod).map(_.asMethod).filter(_.isConstructor)
val mConstructorsParams = mConstructors.map(_.paramss.flatten.map(_.typeSignature))
def of[A: WeakTypeTag](a: A): Boolean = {
val tA = implicitly[WeakTypeTag[A]].tpe
mConstructorsParams.exists{tParams =>
tParams.size == 1 && tA <:< tParams(0)
}
}
def of[A: WeakTypeTag, B: WeakTypeTag](a: A, b: B): Boolean = {
val tA = implicitly[WeakTypeTag[A]].tpe
val tB = implicitly[WeakTypeTag[B]].tpe
mConstructorsParams.exists{tParams =>
tParams.size == 2 && tA <:< tParams(0) && tA <:< tParams(0) && tB <:< tParams(1)
}
}
}
def hasCtor[T: WeakTypeTag]() = new TypeCheck[T]
class Hoge(i: Int, j: String){ def this(j: String) = this(10, j) }
class Fuga(i: String, j: AnyRef){ def this(j: AnyRef) = this("fuga", j) }
scala> hasCtor[Hoge] of (10, "")
res22: Boolean = true
scala> hasCtor[Hoge] of (10, 10)
res23: Boolean = false
scala> hasCtor[Hoge] of (10)
res24: Boolean = false
scala> hasCtor[Hoge] of ("hoge")
res25: Boolean = true
scala> hasCtor[Fuga] of ("fuga", 10)
res26: Boolean = false
scala> hasCtor[Fuga] of ("fuga", "fuga")
res27: Boolean = true
scala> hasCtor[Fuga] of (10)
res28: Boolean = false
scala> hasCtor[Fuga] of (new AnyRef)
res29: Boolean = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment