jeudi 10 septembre 2015

scala: serializable alternatives to java.lang.reflect.Field

Suppose User is a case class that holds information about a user:

case class User(name: String, age: Int)

given a field name (e.g. "name" or "age"), I want to return a function that extract this field (without parsing the field name again). In short, I needed this to work:

val u = User(name = "john",age = 44)
val func = extractFunctionFromFieldName("name") // returns func: User => Any
func(u) // return "john"

Reading about reflection, I got something like this to work:

def extractFunctionFromFieldName(s: String): User => Any = {
  val f = classOf[User].getDeclaredField(s)
  f.setAccessible(true)
  u: User => f.get(u)
}

The problem is that this function is not serializable since java.lang.reflect.Field is not serializable.

Any suggestions or alternatives?

Notes / more background:

  • The list of fields is much larger than just {name,age} and is constantly growing. That's why I want to avoid hard-coding
  • Using productElement should work without serialization issues since fields are replaced with numbers. But I understand there are no guarantees on the order of the product elements.
  • BTW, I need it to be serializable since I am using this with apache spark.




Aucun commentaire:

Enregistrer un commentaire