考慮下面的代碼:如何獲取使用Scala反射的方法的返回類型字符串?
object Foo{def foo(a:Int):List[(String, Int)] = ???}
class Bar{def bar(a:Int, b:Any):Option[(String, Long)] = ???}
鑑於無論是對象或類,我需要先找到方法名(似乎並不那麼困難)。
之後,對於每種方法,我想查找返回類型(不是Java類型)的Scala的字符串描述。因此,例如,對於Foo.foo
,我需要字符串List[(String, Int)]
和Bar.bar
,我需要字符串Option[(String, Long)]
。
編輯:這是一個基於評論我的嘗試:
class RetTypeFinder(obj:AnyRef) {
import scala.reflect.runtime.{universe => ru}
val m = ru.runtimeMirror(getClass.getClassLoader)
val im = m.reflect(obj)
def getRetType(methodName:String) = {
ru.typeOf[obj.type].declaration(ru.TermName(methodName)).asMethod.returnType
}
}
object A { def foo(a:Int):String = ??? } // define dummy object
class B { def bar(a:Int):String = ??? } // define dummy class
val a = new RetTypeFinder(A)
a.getRetType("foo") // exception here
val b = new RetTypeFinder(new B)
b.getRetType("bar") // exception here
我得到的錯誤是:
scala.ScalaReflectionException: <none> is not a method
at scala.reflect.api.Symbols$SymbolApi$class.asMethod(Symbols.scala:228)
at scala.reflect.internal.Symbols$SymbolContextApiImpl.asMethod(Symbols.scala:84)
at cs.reflect.Test.getRetCls(Test.scala:11)
...
然而,這個工程(在REPL試過):
import scala.reflect.runtime.{universe => ru}
val m = ru.runtimeMirror(getClass.getClassLoader)
object A { def foo(a:Int):String = ??? } // define dummy object
val im = m.reflect(A)
ru.typeOf[A.type].declaration(ru.TermName("foo")).asMethod.returnType
class B { def bar(a:Int):String = ??? } // define dummy class
val im = m.reflect(new B)
ru.typeOf[B].declaration(ru.TermName("bar")).asMethod.returnType
我需要在第一種方式使用它,我不知道什麼對象/類將被傳遞。任何幫助將不勝感激。
對於類:typeof運算(酒吧)。成員。(newTermName( 「富」))asMethod.returnType – Samar
爲對象的作品相同,以及:'TYPEOF [Foo.type]。成員。( TermName(「foo」))。asMethod.returnType' – Kolmar
@Kolmar請參閱我的編輯,瞭解更多詳細信息。 – Jus12