简体   繁体   中英

Number of attributes of a case class in Scala

What is the most efficient way to get the number of attributes of a case class in Scala? I need to do this before any instantiation.

For instance for the case class:

Person(name: String, weight: Float)

I would like to do something like:

Person.attributes_length // returning 2

With an instance

You can make a "fake" instance or if you have one:

Person(null, 0).productArity

By reflection

Another option is to use reflection.

Scala 2.11

Add the reflection lib to SBT:

"org.scala-lang" % "scala-reflect" % "2.11.8"

And do:

weakTypeOf[Person].decl(termNames.CONSTRUCTOR).asMethod.paramLists.size

Scala 2.10

Add the reflection lib to SBT:

"org.scala-lang" % "scala-reflect" % "2.10.6"

And do:

import scala.reflect.runtime.universe._

weakTypeOf[Person].declaration(nme.CONSTRUCTOR).asMethod.paramss.head.size

Cheers

For the sake of completeness, I ended up using the dependency:

libraryDependencies += "org.scala-lang" % "scala-reflect" % "2.10.4"

with the code:

import scala.reflect.runtime.universe._
val length = weakTypeOf[Person].declaration(scala.reflect.runtime.universe.nme.CONSTRUCTOR).asMethod.paramss.head.length

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM