在Java中,我可以将一个变量保持为只读吗?这在编译时或运行时都可以吗?

huangapple go评论138阅读模式
英文:

Can I keep a variable read-only in Java? It'a all ok in compile time or runtime

问题

我是一个Java新手。我想在特定范围内使一些变量成为只读的,我应该怎么做?
我可以添加一些语法规则吗?或者有其他方法可以实现吗?

示例:

public void func(Object obj); // 如何使变量obj成为只读?
英文:

I'm a Java newbie. I want to make some variable read-only in some special scope.how can I do it?
Can I add some rules of grammar? Or there are any way work?

sample:

public void func(Object obj); // how can i make variable obj read-only?

答案1

得分: 3

尝试这个:

public void func(final Object obj);

当一个变量使用final关键字声明时,其值不能被修改。这意味着使用final声明的引用变量永远不能重新分配以引用不同的对象。

对象内部的数据可以被更改,对象的状态可以被更改,但引用不能被更改。

英文:

Try this:

public void func(final Object obj); 

When a variable is declared with the final keyword, its value can’t be modified. That means a reference variable declared final can never be reassigned to refer to a different object.

The data within the object can be changed. the state of the object can be changed but not the reference.

答案2

得分: 1

将方法改成这样:

public void func(final Object obj) {...}

在方法体内,您只能读取变量,但不能对其赋值,因此它是只读的。
final 表示您只能一次赋值给变量。
-> final double pi = 3.14159265359d;)

英文:

<br>
make the method look like this:

public void func(final Object obj) {...}

inside of the method body you can only read the variable but cannot assign any value to is. so its read-only.<br>
(final means, that you can only assign once an value to an variable<br>
-> final double pi = 3.14159265359d; )

答案3

得分: 1

将其更改为 public void func(final Object obj);

但要小心,对象本身仍然可以更改。
看这个例子:

List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
System.out.println(list);//[1,2,3]
foo(list);
System.out.println(list);//[1,2,3,4],列表被改变了。
....
public void foo(final List<Integer> list){
   list.add(4);
}
英文:

Change it to public void func(final Object obj); .

But be cautious, the object itself can still be changed.
See this example:

List&lt;Integer&gt; list=new ArrayList&lt;&gt;();
list.add(1);
list.add(2);
list.add(3);
System.out.println(list);//[1,2,3]
foo(list);
System.out.println(list);//[1,2,3,4], the list was mutated.
....
public void foo(final List&lt;Integer&gt; list){
   list.add(4);
}

</details>



# 答案4
**得分**: 1

你可以将变量声明为 `final`,例如 `final MyClass obj = aVal`,以防止分配除了第一次分配之外的其他内容。但是,请注意,`obj` 仍然可以被修改,即 `obj = someOtherVal` 是不可能的,但如果在 `MyClass` 中存在一个名为 `setX` 的 setter 方法,你可以执行 `obj.setX(...)`。

只有通过将类定义为不可变的,然后使用关键字 `final` 声明其变量,才能防止重新分配和修改两者。

<details>
<summary>英文:</summary>

You can declare a variable as `final` e.g. `final MyClass obj = aVal` to prevent assigning something other than the first assignment. However, note that `obj` can still be modified i.e. `obj = someOtherVal` is not possible but you can do `obj.setX(...)` if there is a setter method `setX` in `MyClass`.

The only way both re-assignment and modification can be prevented is by defining the class as immutable and then declaring a variable of it with the keyword, `final`. 

</details>



# 答案5
**得分**: 1

你可以将一个带有 `final` 关键字的对象传递给 `func(Object obj)` 方法。

请查看下面的示例:

```java
public class FinalExample {

    public static void main(String[] args) {

        FinalExample ex = new FinalExample();

        A a = new A();
        a.setI("Test");

        ex.func(a);

    }

    public void func(final A a) {

        System.out.println(a.getI());
    }

}

public class A {

    public String i;

    public String getI() {
        return i;
    }

    public void setI(String i) {
        this.i = i;
    }

}
英文:

You can pass an object with final keyword to func(Object obj).

Please check below sample example

public class FinalExample {

	public static void main(String[] args) {
	
		FinalExample ex = new  FinalExample();
		
		A a = new A();
		a.setI(&quot;Test&quot;);
	
		ex.func(a);
		
	}
	
	public void func(final A a) {
		
		System.out.println(a.getI());
	}
	
}


public class A {

	public String i;

	public String getI() {
		return i;
	}

	public void setI(String i) {
		this.i = i;
	}
	
}

huangapple
  • 本文由 发表于 2020年8月7日 19:48:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/63301207.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定