简体   繁体   English

Java - 在构造函数中设置后,任何使变量不可修改的方法?

[英]Java - Any way to make variable unmodifiable after being set in the constructor?

I have a member variable that in a class that I want to make sure nothing changes it after it is set in the constructor. 我有一个成员变量,在类中我想确保在构造函数中设置后没有任何更改。 So, it would look something like this: 所以,它看起来像这样:

public class MyClass
{
    private String myVar = null;

    public MyClass(DataObj dataObj)
    {
        myVar = dataObj.getFinalVarValue();
        //at this point I don't want anything to be able change the value of myVar
    }

    ....
}

My first thought was to see I could just add the final modifier to the variable, but the compiler complains about assigning a value to the final field. 我的第一个想法是看到我可以将final修饰符添加到变量中,但编译器抱怨为最终字段赋值。 Is it possible to accomplish this? 有可能做到这一点吗?

The compiler complains (in the constructor), because you already provide an initialization by writing 编译器抱怨(在构造函数中),因为您已经通过编写提供了初始化

private String myVar = null;

remove the ' = null ' part. 删除' = null '部分。 Add final and assign the value in the constructor. 添加final并在构造函数中指定值。

public class MyClass
{
    private final String myVar;

    public MyClass(DataObj dataObj)
    {
        myVar = dataObj.getFinalVarValue(); // the only assignment/init happens here.
    }

    ....
}

Make it private , and then don't include a setter. 将其设为private ,然后不包含setter。 As long as you never change it in within the class methods, it's immutable. 只要你在类方法中永远不改变它,它就是不可变的。

String objects are already immutable. 字符串对象已经是不可变的。 So adding the private final modificator is enough. 因此添加私有最终修改器就足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java不可修改集合强制转换为枚举 - Java unmodifiable set casted to an enumset Java - 不可修改的键集映射 - Java - unmodifiable key set map Java 8 Lambda指定地图类型并使其不可修改 - Java 8 Lambda specify map type and make it unmodifiable 使用Java进行调试时,是否有办法检测ANY变量是否设置为给定值? - When Debugging in Java, is there a way to detect if ANY variable is set to a given value? 有什么方法可以让java中的前5名显示变量名? - Any way to make a top 5 in java displaying the variable names? 是否有Java构建方式可以将2个整数组合成一个Set? - Is there any build in Java way to make a Set out of a combination of 2 ints? java集合的不可修改的包装器是否使它们对线程安全? - Does the unmodifiable wrapper for java collections make them thread safe? 在 Java 中,有没有办法在同一个构造函数中调用 this() 和 super()? - In Java, is there any way to call this() and super() in same constructor? 在Java中_not_调用超类构造函数的任何方法? - Any way to _not_ call superclass constructor in Java? 构造函数中加载的Java属性值将在构造函数之后恢复吗? - Java property values loaded in constructor are being reverted after the constructor?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM