Scala进阶之路-反射(reflect)技术详解

            Scala进阶之路-反射(reflect)技术详解

                                作者:尹正杰

版权声明:原创作品,谢绝转载!否则将追究法律责任。

 

 

  Scala中的反射技术和Java反射用法类似,我这里就不一一介绍反射是啥了,如果对Java的反射感兴趣的话可以参考我之前分享的笔记:https://www.cnblogs.com/yinzhengjie/p/9272289.html。好了,废话不多说,我们直接上一个Scala的案例。

 

 

 

 1 /*
 2 @author :yinzhengjie
 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Scala%E8%BF%9B%E9%98%B6%E4%B9%8B%E8%B7%AF/
 4 EMAIL:y1053419035@qq.com
 5 */
 6 package cn.org.yinzhengjie.scalaReflect
 7 
 8 class Person(name:String,age:Int) {
 9     def sayHello() = {
10         println(s"Hi,I'm ${name},Nice to meet you!")
11     }
12 
13     def palyGame(msg:String) = {
14         println(s"${name} 正在玩《${msg}》,这局已经拿下了8次五杀了.......")
15     }
16 
17 
18     override def toString: String = {
19         s"姓名:${name},年龄:${age}"
20     }
21 
22 }
23 
24 
25 object PersonDemo {
26     def main(args: Array[String]): Unit = {
27         //得到JavaUniverse用于反射(获取Environment和universe)
28         val ju = scala.reflect.runtime.universe
29         //得到一个JavaMirror,用于反射Person.class(获取对应的Mirrors,这里是运行时的)
30         val mirror = ju.runtimeMirror(getClass.getClassLoader)
31         //得到Person类的Type对象后,得到type的特征值并转为ClassSymbol对象
32         val classPerson = ju.typeOf[Person].typeSymbol.asClass
33         //用Mirrors去reflect对应的类,返回一个Mirrors的实例,而该Mirrors装载着对应类的信息
34         val classMirror = mirror.reflectClass(classPerson)
35         //得到构造器方法
36         val constructor = ju.typeOf[Person].decl(ju.termNames.CONSTRUCTOR).asMethod
37         //得到MethodMirror
38         val methodMirror = classMirror.reflectConstructor(constructor)
39         /**
40           * Scala通过反射实例化对象
41           */
42         val p = methodMirror("yinzhengjie",18)
43         println(p.toString)
44 
45         /**
46           * Scala通过反射调用方法
47           */
48         val instanceMirror = mirror.reflect(p)
49         //得到Method的mirror
50         val mysayHelloMethod = ju.typeOf[Person].decl(ju.TermName("sayHello")).asMethod
51         val mypalyGameMethod = ju.typeOf[Person].decl(ju.TermName("palyGame")).asMethod
52         //通过Method的Mirror索取方法
53         val mysayHello = instanceMirror.reflectMethod(mysayHelloMethod)
54         val mypalyGame = instanceMirror.reflectMethod(mypalyGameMethod)
55         //调用我们自定义的方法
56         mysayHello()
57         mypalyGame("英雄联盟")
58 
59         /**
60           * Scala通过反射访问属性
61           */
62         val nameField = ju.typeOf[Person].decl(ju.TermName("name")).asTerm
63         val name = instanceMirror.reflectField(nameField)
64         println("通过反射得到name的值为:"+name.get)
65     }
66 }
67 
68 
69 /*
70 以上代码执行结果如下:
71 姓名:yinzhengjie,年龄:18
72 Hi,I'm yinzhengjie,Nice to meet you!
73 yinzhengjie 正在玩《英雄联盟》,这局已经拿下了8次五杀了.......
74 通过反射得到name的值为:yinzhengjie
75  */

 

posted @ 2018-07-29 13:44  尹正杰  阅读(2872)  评论(0编辑  收藏  举报