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?
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
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With