use*_*807 5 java static-analysis
我在Eclipse中使用静态分析器来检查我的代码.一个班,foo,有一个内部类,吧.我收到以下错误:
JAVA0043 Inner class 'bar' does not use outer class 'foo'
Run Code Online (Sandbox Code Playgroud)
为什么这是一个错误?只要外部类使用内部类不足以使这些信息隐藏有用且正确吗?
内部类不是静态的.
Von*_*onC 11
看起来像Enerjy错误:
// Incorrect
class Log {
// Position never uses the enclosing Log instance,
// so it should be static
class Position {
private int line;
private int column;
Position(int line, int column) {
this.line = line;
this.column = column;
}
}
}
Run Code Online (Sandbox Code Playgroud)
不使用任何实例变量或来自任何外部类的方法的嵌套类可以声明为static.
这减少了两个类之间的依赖性,从而增强了可读性和维护性.
// Correct
class Log {
static class Position {
private int line;
private int column;
Position(int line, int column) {
this.line = line;
this.column = column;
}
}
}
Run Code Online (Sandbox Code Playgroud)
非静态内部类具有对其外部类的实例的隐式引用.这个隐藏的引用可以延迟(甚至阻止)外部类的垃圾收集并创建序列化问题.所以你应该只在需要时使用非静态内部类.很容易忘记将类声明为静态,因此代码分析会在不需要时向您发出警告.
| 归档时间: |
|
| 查看次数: |
363 次 |
| 最近记录: |