2016-04-11 31 views
0

我有一个简单的案例类定义如下:获取所有字段以及它们在案例教学法的类型的列表

case class Foo(f1 : String, f2:String) 

我想使用反射来查询该Foo类型,它所有的声明字段,获取这些字段的类型,然后获取与这些类型关联的方法。所以在这个例子中,它会得到字段f1f2,然后对于那些字段,它将确定它们的类型,在这种情况下为String,然后获取与String类型关联的所有方法。

我试过如下:

scala> import reflect.runtime.{universe => ru} 
import reflect.runtime.{universe=>ru} 

scala> case class Foo(f1 : String, f2:String) 
defined class Foo 

scala> ru.typeOf[Foo].declarations 
warning: there was one deprecation warning; re-run with -deprecation for details 
res30: reflect.runtime.universe.MemberScope = SynchronizedOps(value f1, value f1, value f2, value f2, constructor Foo, method copy, method copy$default$1, method copy$default$2, method productPrefix, method productArity, method productElement, method productIterator, method canEqual, method hashCode, method toString, method equals) 

第一个问题是,为什么f1f2在此列表中出现两次?

我无法在类型f1获取和f2这里,所以我试图

scala> ru.typeOf[Foo].getClass.getFields 
res31: Array[java.lang.reflect.Field] = Array(public final scala.reflect.api.Universe scala.reflect.api.Types$TypeApi.$outer) 

但这看起来并不像它的检索领域f1f2

我该如何用scala实现我需要的功能?

回答

1

第一个问题是为什么f1和f2在此列表中出现两次?

这两个字段和它的getter方法。

ru.typeOf [美孚] .getClass.getFields

typeOf[Foo]返回Type。所以typeOf[Foo].getClass将返回一个类实现Type,而不是Foo。只需写classOf[Foo].getDeclaredFields。或者如果你想使用scala-reflect类型:

ru.typeOf[Foo].declarations.collect { 
    case t: TermSymbol if t.isCaseAccessor => t 
} 
相关问题