FindBugs error: Write to static field from instanc

2019-03-26 13:25发布

I have couple of areas in my application where I get the error while manipulating value of static variable from instance method.

"Write to static field from instance method".

If we take multi-threading out of the equation, does this scenario pose any potential issue even if multiple instances write to the same static variable ?

1条回答
smile是对你的礼貌
2楼-- · 2019-03-26 14:00

From the documentation...

This instance method writes to a static field. This is tricky to get correct if multiple instances are being manipulated, and generally bad practice.

  • Firstly it says that it is a bad practice, not incorrect.
  • Second thing is the question, about posing any potential issue

    If you are manipulating a static field from instance method, any object of class( class that contains our instance method) may be calling that method and it will be difficult to find out the object manipulating static field in some large application or application that is already developed and coded by others.

This Answer may help you also.

EDIT :

FYI, You can bypass the warning of findbug in following code.

class TestClass {

     static int testInt = 0 ;

     public static setTestInt ( int a ) {
          TestClass.testInt = a ;
     }

     public void setInt ( int a1 ) {
          setTestInt ( a1 ); 
     }
}
查看更多
登录 后发表回答