作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在阅读本网站的教程。 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/
我是一名优秀的程序员,十分优秀!