Domanda

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 ?

È stato utile?

Soluzione

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 ); 
     }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top