Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
896 views
in Technique[技术] by (71.8m points)

scala - Get field names list from case class

I need to get only field names of case class. I'm not interested in its values. I thought getClass.getDeclaredFields.map(_.getName) would return a list of field names.

scala> case class User(id: Int, name: String)
defined class User

scala> User.getClass.getDeclaredFields
res14: Array[java.lang.reflect.Field] = Array(public static final User$ User$.MODULE$)

scala> User.getClass.getDeclaredFields.toList
res15: List[java.lang.reflect.Field] = List(public static final User$ User$.MODULE$)

scala> val user = User(1, "dude")
user: User = User(1,dude)

scala> user.getClass.getDeclaredFields.toList
res16: List[java.lang.reflect.Field] = List(private final int User.id, private final java.lang.String User.name)

What is this User$.MODULE$? What's that?

Method getDeclaredFields works fine when you have an instance of a case class, but I don't want to create an instance in order to get only fields.

Why this isn't true: User.getClass.getDeclaredFields.map(_.getName) == List("id", "name")?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

By using User.getClass, you are referring to the class companion object that Scala by default creates for the case class, and not the case class itself. To get the class object of the case class, use classOf[User].

Alternatively, you could use Scala's reflection API to get the metadata of a case class, which gives you much more information:

import scala.reflect.runtime.universe._

def classAccessors[T: TypeTag]: List[MethodSymbol] = typeOf[T].members.collect {
  case m: MethodSymbol if m.isCaseAccessor => m
}.toList

Test in sbt console:

scala> case class User(name: String, age: Int)
defined class User

scala> classAccessors[User]
res0: List[reflect.runtime.universe.MethodSymbol] = List(value age, value name)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...