@xtccc
2017-01-04T15:34:35.000000Z
字数 589
阅读 1736
Java
下面用scala的代码来举例
package cn.gridx.scala.lang.reflections
/**
* Created by tao on 1/4/17.
* 利用反射创建一个cn.gridx.scala.lang.reflections.A实例
* 并且创建时传入构造的参数
* A是base的子类
*/
object NewInstance {
def main(args: Array[String]): Unit = {
val clz = Class.forName("cn.gridx.scala.lang.reflections.A")
val con = clz.getConstructor(classOf[Map[String, String]])
val obj = con.newInstance(Map("1" -> "100", "2" -> "200")).asInstanceOf[Base]
obj.show()
}
}
trait Base {
def show(): Unit = ???
}
class A(attribute: Map[String, String]) extends Base {
override
def show(): Unit = {
println(s"A: attribute = $attribute")
}
}