Scala反射错误:这是一个内部模块,在InstanceMirror上使用reflectModule来获取它的ModuleMirror [英] Scala reflection error: this is an inner module, use reflectModule on an InstanceMirror to obtain its ModuleMirror

查看:9
本文介绍了Scala反射错误:这是一个内部模块,在InstanceMirror上使用reflectModule来获取它的ModuleMirror的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

跟进this question,我试图弄清楚如何在对象上调用方法.相关定义为:

Following up on this question, I'm trying to figure out how to call a method on an object. The relevant definitions are:

trait ThirdParty { def invoke = println("right") }
trait WeatherIcon { def invoke = println("wrong") }
class MyClass {
    object objA extends ThirdParty
    object objB extends WeatherIcon
}

我得到了一个 objASymbol,如下所示:

I got a Symbol for objA like this:

import reflect.runtime.universe._

val stuff = typeOf[MyClass].members.filter(_.isValue).filter(_.typeSignature <:< typeOf[ThirdParty])

这会返回一个带有单个元素的 Iterable,所以让我们说:

That returns an Iterable with a single element, so let's say:

val objASymbol = stuff.head.asModuleSymbol

然后我尝试了,基于this other question,这个:

I then tried, based on this other question, this:

val mirror = runtimeMirror(getClass.getClassLoader)
mirror.reflectModule(objASymbol)

导致该主题引用的错误消息:

Which resulted in the error message quoted on the subject:

java.lang.Error: this is an inner module, use reflectModule on an InstanceMirror to obtain its ModuleMirror
    at scala.reflect.runtime.JavaMirrors$JavaMirror.reflectModule(JavaMirrors.scala:118)
    at scala.reflect.runtime.JavaMirrors$JavaMirror.reflectModule(JavaMirrors.scala:60)

问题是我无法弄清楚这条错误消息告诉我要做什么!

The problem is that I can't figure out what this error message is telling me to do!

推荐答案

需要编写runtimeMirror.reflect().reflectModule(objASymbol).普通的 reflectModule 不行,因为 objA 上的一些反射操作(例如获取它的实例)需要一个外部实例.

You need to write runtimeMirror.reflect(<instance of MyClass>).reflectModule(objASymbol). Plain reflectModule won't do, because some reflective operations on objA (e.g. getting its instance) require an outer instance.

不幸的是,即使你写对了,你的用例也不会起作用,因为 M4 只支持静态对象:https://issues.scala-lang.org/browse/SI-5498.我们会在 2.10.0-final 之前实现这个.

Unfortunately, your use case won't work even if you write it right, because M4 only supports static objects: https://issues.scala-lang.org/browse/SI-5498. We'll implement this before 2.10.0-final.

这篇关于Scala反射错误:这是一个内部模块,在InstanceMirror上使用reflectModule来获取它的ModuleMirror的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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