2

How to get all public fields (including inherited) and their values from the object of Scala class?

This:

class A(val a: String)

class B(val b: String) extends A("a")

val b = new B("b")

b.getClass.getFields

returns empty list.

Krzysztof Atłasik
  • 21,985
  • 6
  • 54
  • 76
gs_vlad
  • 1,409
  • 4
  • 15
  • 29
  • 1
    A combination of https://stackoverflow.com/questions/7708485/scala-class-getfields and https://stackoverflow.com/questions/2658060/how-to-access-a-fields-value-via-reflection-scala-2-8 should be a good place for you to start. AKA, reflection. – James Whiteley Apr 18 '19 at 15:31
  • 2
    Can you explain why you want to do this? There seems to be an endless stream of people wanting to dynamically unpick data structures, but the reason for wanting to do this is never clear. I fear it is because they are trying to re-create features from another language rather than use the features in Scala. – Tim Apr 18 '19 at 16:51
  • I want to build http request with url params taken from case classes in Scala. I don't want to add some 'parse' method to each such class. My intention is to implement retrieving of values in one place, not in each class. – gs_vlad Apr 19 '19 at 09:31
  • 3
    This sounds like a use case for a _compile time reflection_ rather than _runtime reflection_. So either Shapeless or Scala macros. – Mateusz Kubuszok Apr 19 '19 at 10:03

0 Answers0