如果我们在构造函数中定义了默认值,如何使用Scala反射调用默认构造函数

编程入门 行业动态 更新时间:2024-10-11 23:18:59
本文介绍了如果我们在构造函数中定义了默认值,如何使用Scala反射调用默认构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 class Person(name: String = "noname", age:Int = -1){} object ReflectionTester{ def main(args: Array[String]) { val m = ru.runtimeMirror(getClass.getClassLoader) val classTest = m.staticClass("Person") val theType = classTest.toType //class mirror val cm = m.reflectClass(classTest) val ctor = theType.decl(ru.termNames.CONSTRUCTOR).asMethod } }

调用类镜像为我提供了传递名称和年龄的默认构造函数,但是推断出的构造函数太正确了,在这里我可以创建一个具有默认值的人,并允许我根据需要设置它们.

Invoking class mirror gives me the default constructor of passing name and age but there are inferred constructor too right where i can create a person with default values and allow me to set them as needed.

如何在方法镜像中调用它.在这种情况下,我期望有4个构造函数,分别具有两个值和2个独立字段,以及1个没有字段.

How do you invoke that in method mirror. I'm expecting 4 constructors in this case 1 with both values and 2 for individual fields and 1 with no fields.

我选择此作为示例VO,因此请不要对设计发表评论.问题是如何推断默认值的构造函数

I choose this as an example VO so please don't comment on the design. The question is on how to infer the constructors with default values

推荐答案

只有一个构造函数.默认值保留在人"随行对象中.呼叫 new Person(年龄= 10)会变成类似 new Person(Person.< init> $ default $ 1(),10).

There is only one constructor. The default values are kept in the Person companion object. A call new Person(age = 10) is turned into something like new Person(Person.<init>$default$1(), 10).

更多推荐

如果我们在构造函数中定义了默认值,如何使用Scala反射调用默认构造函数

本文发布于:2023-11-12 09:53:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581166.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   如何使用   反射   默认值   定义

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!