Find synthetic members in class fields in Scala
Asked Answered
D

1

5

I am using the following method in scala to get hold of all the fields in a class:

  val fields = contract.getClass.getDeclaredFields.toList.map(value => {
  value.setAccessible(true)
  value.getName
})

contract has been defined as a class in my code. Since I am using reflection, the problem is I get another element $jacocoData as one of the fields. I want to ignore this field. The 'hacky' way of doing it is to know the fact that it is always appended at the end of the list, so I can 'fix' it by changing my function signature to include productArity and only take the first arity number of elements like this:

  def getFields(contract: Contract, arity: Int): List[String] = {
     val fields = contract.getClass.getDeclaredFields.toList.map(value => {
     value.setAccessible(true)
     value.getName
  })
 //to ignore $jacocoData (Java code coverage) field
 val firstnFields = fields.take(arity)
 firstnFields
 }

According to the last point of this FAQ, I need to get rid off synthetic members of a class. How do I do that?

Ditter answered 11/12, 2013 at 12:37 Comment(0)
M
7

Simply assuming that $jacocoData is always the last element is dangerous, as Class#getDeclaredFields() does not guarantee any order.

To check whether a field is synthetic use Field#isSynthetic(), so your code can be changed to:

val fields = contract.getClass.getDeclaredFields.
 toList.withFilter(!_.isSynthetic()).map(value => {
  value.setAccessible(true)
  value.getName
 })                                              
Matri answered 11/12, 2013 at 13:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.