【问题标题】:How to create a public static variable that is modifiable only from their class?如何创建一个只能从他们的类中修改的公共静态变量?
【发布时间】:2015-11-03 11:07:00
【问题描述】:

我有两个班级:

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
    }
}

问:我可以只从他的类中创建可修改的成员吗,因为其他类是不变的?

【问题讨论】:

  • 将设置器设为私有
  • 如果定义它的类可以修改该字段,那么它不是常量

标签: java class static member public


【解决方案1】:

不,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.
}

【讨论】:

  • 我知道我需要创建一个私有变量和公共getter。我想知道它是否可以是另一种方式,但谢谢你:)
  • @Kumas.r.o 不客气。是的,这是唯一的方法,除非您将字段设置为 final,这可能不是您要在这里寻找的。​​span>
【解决方案2】:

只需删除setter 并创建变量private。然后其他类只能读取 stetted 的值。

public class a {
 private static int var=2;
 public static int getVar() {
    return var; 
 }
}

但是当你来到Javareflection时没有这样的保护。

【讨论】:

    【解决方案3】:

    答案是 你不能让一个公共静态变量只从它的类中修改你可以让变量私有并且只有公共getter或者你可以添加设置器私有

    【讨论】:

      猜你喜欢
      • 2015-04-07
      • 2022-11-14
      • 2012-05-11
      • 2017-03-23
      • 1970-01-01
      • 1970-01-01
      • 2013-02-01
      • 2015-03-19
      • 1970-01-01
      相关资源
      最近更新 更多