我期待hello =「hello」,但它打印出null。我可以知道是什麼原因?爲什麼JUnit方法引用對象?
@Test
public void testGetABC(){
String hello= null;
assembleABC(hello);
System.out.println(hello); // null
}
public static void assembleABC(String hello){
hello = "hello";
}
我期待hello =「hello」,但它打印出null。我可以知道是什麼原因?爲什麼JUnit方法引用對象?
@Test
public void testGetABC(){
String hello= null;
assembleABC(hello);
System.out.println(hello); // null
}
public static void assembleABC(String hello){
hello = "hello";
}
EDITED
在Java參數是按值傳遞,而不是引用,你實際上是不修改hello
。這意味着對象本身的內部狀態可能會改變,但不是您在方法調用中使用的引用(變量)。
也許知道C#,在那裏你可以通過參考發送參數,但是這在Java中是不可能的:
@Test
public void testGetABC(){
String hello= null;
assembleABC(byRef hello); // NOT really allowed, compilation error
System.out.println(hello);
}
public static void assembleABC(byRef String hello){ // NOT really allowed, compilation error
hello = "hello";
}
你可以做的來解決問題是要改變這樣的代碼:
@Test
public void testGetABC(){
String hello= null;
hello = assembleABC();
System.out.println(hello); // not null anymore
}
public static String assembleABC(){
return "hello";
}
在java函數中的值是通過refrence方法傳遞的。 所以如果你改變了對象引用的值,那麼值就會被反映出來。 但是如果你改變了參考本身,那麼它們不會有任何效果。 在java中String是不可變的對象。
檢查下面的例子更多的澄清:
public class Test
{
/**
* @param args
*/
public static void main(String[] args)
{
String hello = "hello";
StringBuffer strBuffer = new StringBuffer("hello");
changeMe(hello);
System.out.println(hello);
changeMe(strBuffer);
System.out.println(strBuffer);
changeMe2(strBuffer);
System.out.println(strBuffer);
}
public static void changeMe(String hello){
hello = null;
}
public static void changeMe(StringBuffer strBuffer){
strBuffer.append("appended");
}
public static void changeMe2(StringBuffer strBuffer){
strBuffer = null;
}
}
輸出:
你好
helloappended
helloappended
在Java中,字符串總是不變的。如果你想把一個引用傳遞給一個函數,你可以創建你自己的(不是最終的)類,並把字符串放在那裏。
下面是一個簡單的例子:我叫我自己的類VariableString:
public class StringTest {
private class VariableString {
private String string;
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
public int length() {
return this.string.length();
}
public String toString() {
return string;
}
}
public static void assembleABC(VariableString hello) {
hello.setString("hello");
}
public static void main(String[] args) {
VariableString hello = new StringTest().new VariableString();
assembleABC(hello);
System.out.println(hello); // prints hello
}
}
嘗試做的JUnit之外,將工作..我只是用一個簡單的例子。 – seesee
@seesee相信我,它在你嘗試的方式不起作用 – morgano
我會建議這一點。基本範圍問題。 OP不理解範圍或方法(至少一些核心概念缺失)。良好的迴應,@morgano –