如何创建一个只能从 class 修改的 public 静态变量?
How to create a public static variable that is modifiable only from their class?
我有两个 classes:
class a {
public static int var;
private int getVar() {
return var; //Yes
}
private void setVar(int var) {
a.var = var; //Yes
}
}
class b {
private int getVar() {
return a.var; //Yes
}
private void setVar(int var) {
a.var = var; //No
}
}
问:我能否仅从他的 class 中创建可修改成员,因为其他 classes 将保持不变?
只需删除 setter
并创建变量 private
。那么其他class只能读取stetted的值。
public class a {
private static int var=2;
public static int getVar() {
return var;
}
}
但是到了Java
reflection
就没有这样的保护了
不,public
访问修饰符基本上允许您从代码库中的任何位置修改引用的值。
您可以做的是根据您的特定需要使用 private
或限制较少的访问修饰符,然后实现 getter,但没有 setter。
在后一种情况下,请记住添加一些逻辑以防止可变对象(例如集合)发生变异。
例子
class Foo {
// primitive, immutable
private int theInt = 42;
public int getTheInt() {
return theInt;
}
// Object, immutable
private String theString = "42";
public String getTheString() {
return theString;
}
// mutable!
private StringBuilder theSB = new StringBuilder("42");
public StringBuilder getTheSB() {
// wrapping around
return new StringBuilder(theSB);
}
// mutable!
// java 7+ diamond syntax here
private Map<String, String> theMap = new HashMap<>();
{
theMap.put("the answer is", "42");
}
public Map<String, String> getTheMap() {
// will throw UnsupportedOperationException if you
// attempt to mutate through the getter
return Collections.unmodifiableMap(theMap);
}
// etc.
}
答案是否你不能创建一个public静态变量只修改它的class你可以创建变量private 并且只有 public getter 或者您可以添加 setter private
我有两个 classes:
class a {
public static int var;
private int getVar() {
return var; //Yes
}
private void setVar(int var) {
a.var = var; //Yes
}
}
class b {
private int getVar() {
return a.var; //Yes
}
private void setVar(int var) {
a.var = var; //No
}
}
问:我能否仅从他的 class 中创建可修改成员,因为其他 classes 将保持不变?
只需删除 setter
并创建变量 private
。那么其他class只能读取stetted的值。
public class a {
private static int var=2;
public static int getVar() {
return var;
}
}
但是到了Java
reflection
就没有这样的保护了
不,public
访问修饰符基本上允许您从代码库中的任何位置修改引用的值。
您可以做的是根据您的特定需要使用 private
或限制较少的访问修饰符,然后实现 getter,但没有 setter。
在后一种情况下,请记住添加一些逻辑以防止可变对象(例如集合)发生变异。
例子
class Foo {
// primitive, immutable
private int theInt = 42;
public int getTheInt() {
return theInt;
}
// Object, immutable
private String theString = "42";
public String getTheString() {
return theString;
}
// mutable!
private StringBuilder theSB = new StringBuilder("42");
public StringBuilder getTheSB() {
// wrapping around
return new StringBuilder(theSB);
}
// mutable!
// java 7+ diamond syntax here
private Map<String, String> theMap = new HashMap<>();
{
theMap.put("the answer is", "42");
}
public Map<String, String> getTheMap() {
// will throw UnsupportedOperationException if you
// attempt to mutate through the getter
return Collections.unmodifiableMap(theMap);
}
// etc.
}
答案是否你不能创建一个public静态变量只修改它的class你可以创建变量private 并且只有 public getter 或者您可以添加 setter private