score:54
Accepted answer
MethodSymbol
has an isCaseAccessor
method that allows you to do precisely this:
def getMethods[T: TypeTag] = typeOf[T].members.collect {
case m: MethodSymbol if m.isCaseAccessor => m
}.toList
Now you can write the following:
scala> case class Person(name: String, age: Int)
defined class Person
scala> getMethods[Person]
res1: List[reflect.runtime.universe.MethodSymbol] = List(value age, value name)
And you get only the method symbols you want.
If you just want the actual field name (not the value
prefix) and you want them in the same order then:
def getMethods[T: TypeTag]: List[String] =
typeOf[T].members.sorted.collect {
case m: MethodSymbol if m.isCaseAccessor => m.name.toString
}
score:14
If you want to get fancier you can get them in order by inspecting the constructor symbol. This code works even if the case class type in question has multiple constructors defined.
import scala.collection.immutable.ListMap
import scala.reflect.runtime.universe._
/**
* Returns a map from formal parameter names to types, containing one
* mapping for each constructor argument. The resulting map (a ListMap)
* preserves the order of the primary constructor's parameter list.
*/
def caseClassParamsOf[T: TypeTag]: ListMap[String, Type] = {
val tpe = typeOf[T]
val constructorSymbol = tpe.decl(termNames.CONSTRUCTOR)
val defaultConstructor =
if (constructorSymbol.isMethod) constructorSymbol.asMethod
else {
val ctors = constructorSymbol.asTerm.alternatives
ctors.map(_.asMethod).find(_.isPrimaryConstructor).get
}
ListMap[String, Type]() ++ defaultConstructor.paramLists.reduceLeft(_ ++ _).map {
sym => sym.name.toString -> tpe.member(sym.name).asMethod.returnType
}
}
Source: stackoverflow.com
Related Query
- Scala 2.10 reflection, how do I extract the field values from a case class, i.e. field list from case class
- How can I extract values from a String to create a case class instance in Scala
- How to extract boolean values from XML to Scala case class
- How To Access access Case class field Value from String name of the field
- MongoDB Scala driver. How to update only changed document's fields from the case class object
- How to extract the field values from a dataset in spark using scala?
- How to get around the Scala case class limit of 22 fields?
- How to create a Scala class with private field with public getter, and primary constructor taking a parameter of the same name
- How to get the name of a case class field as a string/symbol at compile time using shapeless?
- Scala spark: how to use dataset for a case class with the schema has snake_case?
- Using Scala 2.10 reflection how can I list the values of Enumeration?
- How to check which parameters of case class have default value using scala reflection 2.10
- in scala how to convert one case class to another immune to code changes field additions?
- How to convert the Scala case class definition to Haskell?
- Scala - how to get the 'type' for a field using reflection api
- What's the best way to extract a value from a scala case class?
- scala check if at least one case class field value is nonEmpty using reflection
- How to generate values for case class parameters in scala
- How to extract values from Some() in Scala
- How to get the set of rows which contains null values from dataframe in scala using filter
- Using shapeless to extract data from case classes, modify it, and recreate the case class
- scala - how to access a case class method from another class?
- How to load a class from the source code using reflection inside SBT task?
- How to access case class field annotation values
- How to get Scala case class fields and values as (String, String) with Shapeless or Macro
- How to extract a specific text from the string variable in scala
- Get field names from Scala case class with specific annotation
- In ScalaPb, How to create a case object and case class extending from the same trait?
- How to convert JSON into Scala class (NOT Case class), and then populate set of case classes from that big class
- how to get the annotation of a scala class field
More Query from same tag
- Combinator parser ~ also matches spaces
- When should I declare a parameter as val when injecting it into a class?
- Missing or invalid dependancy on sample Play project
- How is named values for Tuple implemented in swift?
- playframework multiple ports
- Obtain version of Akka HTTP at run time
- AJAX file upload in Play Framework 2.1 RC1 delivers an empty file
- How to override = operator in Scala
- Scala Parser Combinators :Handling Repetition of a type
- How to enable foreign key validation in SQLite with Slick
- Combine two rdds
- Constructor can not be instantiated
- How to handle multiple Promises in an (akka) Actor?
- private field in object doesn't compile
- What is the difference between `Option.fold()()` and `Option.map().getOrElse()`?
- How to trigger a method call every x minutes in Scala?
- How to get the line separator of current os easily in Scala?
- Transform a list of object to lists of its field
- Fibonnaci Sequence fast implementation
- unable to detect empty for Sequence using map function in scala
- Scala extra parentheses printout
- Complexity of List.reverse?
- AbstractMethodError when overriding a Java method with vararg parameter from Scala
- Spark DataFrame filter not working as expected with Random
- Extracting polymorphic types in json4s
- Extract Databricks Cluster dependencies and add them in build.sbt to build jar in Azure DevOps
- why I can update state of an Object extend immutable trait in scala
- Hive SaveAsTable creates a new Parquet table file for every run
- How to parse SBT test reports on Shippable?
- In Play 2 Framework , how can I include git commit sha in sbt dist package name?