通过scala中的反射调用构造函数2.10 [英] Calling a constructor through reflection in scala 2.10

查看:730
本文介绍了通过scala中的反射调用构造函数2.10的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在scala 2.10(M4 +)中调用类的构造函数的最佳做法是什么?

What's the best practice for calling a constructor of a class in scala 2.10 (M4+) ?

推荐答案

回答自己的问题:
调用构造函数不同于调用方法。这是在scala 2.10中正确的方法。

Answering my own question: Calling the constructor is different than invoking a method. Here's the right way to do it in scala 2.10

import reflect.runtime.universe._
import reflect.runtime.currentMirror
val typ = typeOf[Range]
val constructor = typ.members.find(_.kind == "constructor").get.asMethodSymbol
currentMirror reflectClass typ.typeSymbol.asClassSymbol reflectConstructor constructor apply (1,10,1)

如预期,结果是:

res7: Any = Range(1, 2, 3, 4, 5, 6, 7, 8, 9)

这篇关于通过scala中的反射调用构造函数2.10的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆