Java FindBugs 错误:从实例方法写入静态字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21136302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
FindBugs error: Write to static field from instance method
提问by Baz
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 ?
如果我们将多线程排除在外,即使多个实例写入同一个static
变量,这种情况是否会造成任何潜在问题?
采纳答案by Not a bug
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 manipulatingstatic
field in some large application or application that is already developed and coded by others.
- 首先它说这是一种不好的做法,而不是不正确的。
第二件事是关于提出任何潜在问题的问题
如果您正在
static
从实例方法操作字段,则类(包含我们的实例方法的类)的任何对象都可能正在调用该方法,并且static
在某些大型应用程序或已经开发的应用程序中很难找到对象操作字段别人编码的。
This Answermay help you also.
这个答案也可以帮助你。
EDIT :
编辑 :
FYI, You can bypass the warning of findbug in following code.
仅供参考,您可以在以下代码中绕过 findbug 的警告。
class TestClass {
static int testInt = 0 ;
public static setTestInt ( int a ) {
TestClass.testInt = a ;
}
public void setInt ( int a1 ) {
setTestInt ( a1 );
}
}