sonarQube raises Make a static final constant or non-public and provide accessors if needed on JNA structure

I created the following JNA structure which works in my project context :

    @FieldOrder({ "string", "stringSize" })
    public static class stringStruct extends Structure {
        public static class ByReference extends stringStruct implements Structure.ByReference {
        }
        public static class ByValue extends stringStruct implements Structure.ByValue {
        }
        public String string;
        public int stringSize;
    }

I launched sonarQube analysis on my code and sonarQube raises the following error: “Make stringSize a static final constant or non-public and provide accessors if needed.” That’s weird because I have two fields in my structure and only one them raises such an issue.

Anyway, if I’ve correctly understood, regarding this issue I should do something like that to fix the issue on stringSize field :

    @FieldOrder({ "string", "stringSize" })
    public static class stringStruct extends Structure {
        public static class ByReference extends stringStruct implements Structure.ByReference {
        }
        public static class ByValue extends stringStruct implements Structure.ByValue {
        }
        public String string;
        
        private int stringSize;
        
        public int getStringSize() {
            return stringSize;
        }

        public void setStringSize(int stringSize) {
            this.stringSize = stringSize;
        }
    }

But This not the way JNA works, isn’t it? Thus can I assume that there is something wrong with the sonarQube criteria I’m using? And not on my implementation.

Answer

JNA relies on the public modifier for class fields of structures, which are accessed via reflection.

Accessor methods are generally not used, except in convenience, e.g., if you have a byte[] or char[] field that’s intended to be text, you might add a getFooString() accessor method to make fetching that String easier.

So yes, you’ll have to ignore and/or suppress Sonar warnings on those, as they are typically non-compliant. In general, JNA mappings also tend to preserve the case of the field names as well, which Sonar also complains goes against standards! This is not so much a flaw in Sonar — these are generally good rules for your other code. It’s just not the way JNA works.

I try to put all my JNA code in its own package for a few reasons:

  • it makes it easier to exclude the package from certain CI tools like Sonar
  • when migrating to the Java Module System (JPMS), you will need to open the package(s) with JNA structures to com.sun.jna for the Structure class to see them with reflection.
  • it makes it easier for you to go through your code later and find things to contribute to the user mappings in the JNA project and give back to the community!

Leave a Reply

Your email address will not be published. Required fields are marked *