Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find synthetic members in class fields in Scala

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?

like image 373
Core_Dumped Avatar asked Dec 11 '13 12:12

Core_Dumped


1 Answers

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
 })                                              
like image 166
Roland Ewald Avatar answered Nov 03 '22 00:11

Roland Ewald