[关闭]
@xtccc 2017-01-04T07:34:35.000000Z 字数 589 阅读 1599

Reflections

给我写信
GitHub

此处输入图片的描述


Java





1. 从string创建实例


下面用scala的代码来举例

  1. package cn.gridx.scala.lang.reflections
  2. /**
  3. * Created by tao on 1/4/17.
  4. * 利用反射创建一个cn.gridx.scala.lang.reflections.A实例
  5. * 并且创建时传入构造的参数
  6. * A是base的子类
  7. */
  8. object NewInstance {
  9. def main(args: Array[String]): Unit = {
  10. val clz = Class.forName("cn.gridx.scala.lang.reflections.A")
  11. val con = clz.getConstructor(classOf[Map[String, String]])
  12. val obj = con.newInstance(Map("1" -> "100", "2" -> "200")).asInstanceOf[Base]
  13. obj.show()
  14. }
  15. }
  16. trait Base {
  17. def show(): Unit = ???
  18. }
  19. class A(attribute: Map[String, String]) extends Base {
  20. override
  21. def show(): Unit = {
  22. println(s"A: attribute = $attribute")
  23. }
  24. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注