在Java中,private static final
字段是不可变的,这意味着它们的值在初始化后不能被更改。如果您想在类外部修改这个值,可以考虑以下方法:
private static final
字段更改为private static
,并为其创建getter和setter方法。这样,您可以在类外部使用setter方法修改其值。public class MyClass {
private static String myField;
public static String getMyField() {
return myField;
}
public static void setMyField(String newValue) {
myField = newValue;
}
}
private static final
字段放在接口中,并在实现类中提供setter方法。这样,您可以在实现类中使用setter方法修改其值。public interface MyInterface {
String MY_FIELD = "initialValue";
default String getMyField() {
return MY_FIELD;
}
void setMyField(String newValue);
}
public class MyImplementation implements MyInterface {
public void setMyField(String newValue) {
MY_FIELD = newValue;
}
}
请注意,这些方法都不是真正的“修改”private static final
字段的值,而是使用其他方法来实现类似的效果。在Java中,private static final
字段的值通常应该在初始化后保持不变。
领取专属 10元无门槛券
手把手带您无忧上云