如何在Java中使用静态扩展变量



我们有如下base类:

public class Base {
protected static string rule = "test_1";
public static getRule(){
/* get rule value from origin class*/
}
}

我们有一些从base类扩展而来的类。例如:

public class Derived extends Base {
static {
rule = "test_2";
}
}

现在我们想要获得规则变量,但在某些条件下:

  • 如果用户调用Derived.getRule(),则返回test_2
  • 如果在derivedrule变量未初始化,则返回test_1
  • 我不想在所有子类中覆盖getRule来回答这个问题

我该怎么办

问题是,一旦使用(初始化(Derived类,就会更改Base.rule,现在无论实际类是什么,都会返回test_2

因此,该技术必须在没有静态(以这种形式(的情况下完成。有一个分类的、类级别的值。

public class Base {
private static final String BASE_RULE = "test_1";
public String getRule() {
return BASE_RULE;
}
}
public class Derived extends Base {
private static final String DERIVED_RULE = "test_2";
@Override
public String getRule() {
return DERIVED_RULE;
}
}

或者,您可以使用标记接口,但它们不是互斥的,因此不适用于某些getCategory((。

public class Base implements Test1Category {
}
public class Derived extends Base implements Test2Category { ... }
if (base instanceof Test2Category) { ... }

最新更新