很少使用非static初始化,可能会让很多开发者感到困惑。 如果可能,应该重构为标准构造方法或初始化属性的语句。
如下代码:
class MyClass {
private static final Map MY_MAP = new HashMap() {
// Non-Compliant - HashMap should be extended only to add behavior, not for initialization
{
put("a", "b");
}
};
}
应该重构为:
class MyClass {
// Compliant
private static final Map MY_MAP = ImmutableMap.of("a", "b");
}