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?

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
 })                                              

Need Your Help

String response not getting in .getJSON

jquery json

My controller method just return String value. When I called JSON from my view page, I don't see any value.

Https with Tcplistener

c# ssl https tcplistener

I am building an application that can receive requests from a website to perform functionality not available in a browser. I accomplished this using a Tcplistener and then call in to it by performing