A problem with my project what is the function of getDeclareFields return $jacocoData?

1.5k Views Asked by At

code:

Field[] fields = obj.getClass().getDeclaredFields();

obj is a class which has 2 fields .

public class NullInfo implements Data {

    @Idx(0)
    private Integer index;

    @Idx(1)
    private String  fieldName;
}

interface Data is empty .

my problem is : The field length is expected to be only 2. See the screenshot

what is $jacocoData?

2

There are 2 best solutions below

0
On

what is $jacocoData?

quoting JaCoCo FAQ:

My code uses reflection. Why does it fail when I execute it with JaCoCo?

To collect execution data JaCoCo instruments the classes under test which adds two members to the classes: A private static field $jacocoData and a private static method $jacocoInit(). Both members are marked as synthetic.

Please change your code to ignore synthetic members. This is a good practice anyways as also the Java compiler creates synthetic members in certain situation.

Method https://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Field.html#isSynthetic() allows to determine synthetic fields.

0
On

I guess the issue is caused when you run code coverage with Jacoco.

Root Cause:

jacoco will add a static field to your class for the reason @Godin has explained.

Solution:

you need to use Java reflection only on 'original' fields. You can either explicitly exclude the field named '$jacocoData', or you can use annotation as the filter, e,g.

Field field = fields[i];
Idx annotation = field.getAnnotation(Idx.class);
if (annotation == null) {
    continue;
}