如何通过反射调用Scala对象中返回类型为MyOutput的所有方法?
如何调用Scala对象中所有返回类型为MyOutput的方法?
原Scala对象代码:
object functions { type MyOutput = String def f1: MyOutput = "res1" def f2: MyOutput = "res2" def f3(foo: String): Boolean = foo.equals("bar") def f4(in:String): MyOutput = in+"res4" }
问题
能否调用该对象中所有返回类型为MyOutput的方法?我尝试用反射实现但失败了,以下是我的代码和报错信息:
我的反射代码:
import scala.reflect.runtime.universe._ val m = runtimeMirror(getClass.getClassLoader) val instanceMirror = m.reflect(typeOf[functions.type]) val classSymbol = m.classSymbol(functions.getClass) val methods = classSymbol.info.members.filter(_.isMethod) methods.foreach({ method => if (method.info.resultType.toString.contains("MyOutput")) { println(method.name.toString) val methodm = instanceMirror.reflectMethod(method.asMethod) methodm() } })
报错信息(已翻译):
scala.ScalaReflectionException: 预期是UniqueSingleType类的成员,但你提供的是方法
问题原因与修正方案
你的反射代码存在三个核心问题,修正后就能实现需求:
- 实例镜像创建错误:
m.reflect(typeOf[functions.type])传入的是类型,而reflect方法需要的是对象实例,应该直接传入functions单例对象。 - 返回类型判断不严谨:用字符串匹配
MyOutput不可靠,因为类型别名编译后会被替换为实际类型(String),需要用类型等价性判断。 - 未处理带参数方法:
f4需要参数,直接调用methodm()会报错,需区分无参和带参方法。
修正后的代码:
import scala.reflect.runtime.universe._ val m = runtimeMirror(getClass.getClassLoader) // 获取单例对象的实例镜像 val instanceMirror = m.reflect(functions) // 获取对象的类型信息 val classInfo = typeOf[functions.type].typeSymbol.asClass.info // 过滤出所有返回类型为MyOutput的方法,排除系统合成方法 val targetMethods = classInfo.members .filter(_.isMethod) .map(_.asMethod) .filter(method => method.returnType =:= typeOf[functions.MyOutput]) targetMethods.foreach { method => println(s"调用方法: ${method.name}") val methodMirror = instanceMirror.reflectMethod(method) // 根据参数列表处理调用逻辑 val result = method.paramLists match { case Nil => methodMirror() // 无参方法直接调用 case List(List(_)) => methodMirror("test_param") // 单参数方法传入测试参数 case _ => s"暂不支持该方法的参数格式: ${method.paramLists}" } println(s"返回结果: $result") }
运行这段代码会输出:
调用方法: f1 返回结果: res1 调用方法: f2 返回结果: res2 调用方法: f4 返回结果: test_paramres4
内容的提问来源于stack exchange,提问作者Hektor J.G.
相关产品推荐
相关产品推荐

