Created
October 9, 2013 11:02
-
-
Save daimatz/6899542 to your computer and use it in GitHub Desktop.
リフレクションで動的にインスタンスを生成する何か
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.reflect.runtime.{universe => ru} | |
import ru._ | |
case class Hoge(id: Int, title: String) | |
class Fuga[T: TypeTag](orig: T) { | |
val mirror = ru.runtimeMirror(Thread.currentThread.getContextClassLoader) | |
val clazz = mirror.runtimeClass(typeOf[T]) | |
val fields = clazz.getDeclaredFields | |
def dumpClass() { | |
fields.map { field => | |
println(field.getName + ": " + field.getType.getName) | |
} | |
} | |
def getType[U: TypeTag](obj: U) = typeOf[U] | |
def makeInstance(): T = { | |
val constructor = clazz.getConstructor(fields.map(_.getType): _*) | |
val args: Array[AnyRef] = for (field <- fields) yield { | |
field.setAccessible(true) | |
field.get(orig) | |
} | |
} | |
constructor.newInstance(args: _*).asInstanceOf[T] | |
} | |
} | |
object Test { | |
def main(args: Array[String]) { | |
val s = new Fuga[Hoge](Hoge(1, "Ken")) | |
s.dumpClass | |
println(s.makeInstance) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment