2016-05-27 10 views
0

私はクラスを持っている:Scalaでは、返されたクラスメソッドのTypeTagを取得する方法は?

package org.apache.project 

class Foo { 

def bar: List[Bar] = ... 
} 

は、それは私がtypeof演算を取得することができますScalaの反射[一覧[バー]]クラス名から「org.apache.project.Foo」とメソッド名」での方法ですバー"?

ありがとうございました!あなたはTypeとしてFooを持っている場合

答えて

1

はい、あなたにもTypeの方法barの戻り値の型を見つけることができます。

import scala.reflect.runtime.universe._ 

typeOf[Foo]      // Get the type of Foo 
    .decls       // Get Foo's declared members 
    .find(_.name.toString == "bar") // Find the member named "bar" as a symbol 
    .head       // Unsafely access it for now, use Option and map under normal conditions 
    .asMethod      // Coerce to a method symbol 
    .returnType      // Access the return type 
+0

ありがとうございます!まず試してみましょう。 – tribbloid

+0

私はそれが動作するとは思わない、最初の.DeclsはTypeTagで見つからない(時代遅れ?はmemembersでなければならない)第二に、Fooが汎用関数であれば、returnType出力は消去される。 – tribbloid

+0

http://stackoverflow.com/questions/37714572/in-scala-reflection-why-reflection-function-on-typetag-still-has-type-erasure counterの例 – tribbloid

関連する問題