ror上使用reflectModule获取其ModuleMirr

ror上使用reflectModule获取其ModuleMirr

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

问题描述

限时删除!!

紧跟这个问题,我试图弄清楚如何在对象上调用方法.相关定义为:

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
}

我为objA设置了Symbol,如下所示:

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

然后我根据另一个问题,尝试了这个,

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(<instance of MyClass>).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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 22:25