Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid "Possible unsafe assignment to a non-final static field in a constructor" (AssignmentToNonFinalStatic)

Tags:

java

pmd

My code currently suffers from "Possible unsafe assignment to a non-final static field in a constructor" (AssignmentToNonFinalStatic in PMD).

The class is written as a singleton class, the property affected by this warning looks like this

private static String myProperty;

and is filled by this construct:

public SystemPropertyUtils() throws ConfigException {
    someMethodThrowingConfigException();
    myProperty = "someValue" + this.someOtherValueFromAThreadSafeString;
}

Is there an elaborated way to negate this warning?

like image 788
Robert Heine Avatar asked Oct 21 '25 12:10

Robert Heine


1 Answers

Don't set static fields in the constructor. In this case, make the field, non-static.

Otherwise, I would have to suspect you don't need a constructor. Instead you can initialise the static field in a static initialiser block, or static method.

like image 88
Peter Lawrey Avatar answered Oct 24 '25 02:10

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!