Writing to a static variable in an instance method, why is this a bad practice?

后端 未结 6 1890
故里飘歌
故里飘歌 2020-12-15 06:43

I am a little confused here with this findbugs warning in eclipse.

public class MyClass {
    public static String myString;
}


public class AnotherClass {         


        
6条回答
  •  被撕碎了的回忆
    2020-12-15 07:04

    There aren't many use cases for why you would want to change a static field. Remember that if you set this field to a new value that this value has changed for all instances of this class. This might get you into trouble in a multi-threaded environment, where more than one thread is calling doSomething(). Proper synchronisation is required.

    In 99% of all cases, you want your instance methods to change the non-static fields only, which is why findbugs warns you.

    And findbugs isn't clever enough to find out about your instance method indirectly changing the field in your second example :)

提交回复
热议问题