gpt4 book ai didi

java - 将参数赋给另一个变量有什么好处

转载 作者:行者123 更新时间:2023-11-30 07:03:22 25 4
gpt4 key购买 nike

我正在阅读本网站的教程。 http://tutorials.jenkov.com/java-unit-testing/matchers.html我相信作者是很有经验的。我看到了这样的代码。我也看到别人总是喜欢把方法的参数赋值给变量,然后在方法内部使用。这是这条线。 protected 对象 theExpected = expected;

谁能告诉我,这种编码风格有什么好处?这是在试图避免对象状态被更改还是什么?

如果参数不是对象而是原始变量怎么办。

如果它是像 String 这样的不可变对象(immutable对象)呢?谢谢。

public static Matcher matches(final Object expected){

return new BaseMatcher() {

protected Object theExpected = expected;

public boolean matches(Object o) {
return theExpected.equals(o);
}

public void describeTo(Description description) {
description.appendText(theExpected.toString());
}
};
}

这是更新

我刚刚做了另一个测试,看看在我们得到对象后这个参数是否仍然可以访问。

package myTest;


public class ParameterAssignTest {

public static void main(String[] args) {
MyInterface myClass = GetMyClass("Here we go");
System.out.println(myClass.getValue());
System.out.println(myClass.getParameter());
}

public static MyInterface GetMyClass(final String myString){

return new MyInterface() {

protected String stringInside = myString;

@Override
public String getValue() {
return stringInside;
}

@Override
public String getParameter() {
return myString;
}
};
}
}

输出:

Here we go
Here we go

那么这是否意味着即使我们将此参数分配给局部变量它仍然有效?

最佳答案

我不相信分配给 theExpected 会取得任何成就。

正如预期的那样,它可以在匿名类中访问。如果直接在 describeTo 中使用,对象将不会被 GC,并且当声明 expected 的本地范围被保留时,引用将保持有效。

可能您链接到的帖子的作者认为这种明确的风格更具可读性。

关于java - 将参数赋给另一个变量有什么好处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28457389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com