这让我发疯,因为这没有任何意义。
在以下程序中,b
变量未正确设置。 b
应该通过副本传递,但是由于b
是对对象的引用,因此应该可以正常工作,但不能正常工作。
public class A {
private B b;
public void foo() {
System.out.println("the value of b is : " + b);
bar(b);
System.out.println(b.getName());
}
private void bar(B b){
if (b == null) b = new B();
b.setName("me");
}
public class B {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class MainTest {
public static void main(String args[]) {
A a = new A();
a.foo();
}
}
执行后,我得到这个错误:
the value of b is : null
Exception in thread "main" java.lang.NullPointerException
at test.A.foo(A.java:12)
at test.MainTest.main(MainTest.java:6)
最佳答案
当传递对方法的引用时,即传递该引用的副本。因此,如果引用是对可变对象的,则该方法可以对该对象进行突变。但是,如果您在方法中更改引用,则调用者将看不到此更改。
private void bar(B b){
if (b == null) b = new B(); // this cannot change the reference passed by the caller
b.setName("me"); // this can update an instance of B passed from the outside
}
为了使此方法正常工作,您应该确保从不向其传递空引用,或者应返回新创建/修改的实例:
private B bar(B b) {
if (b == null) b = new B();
b.setName ("me");
return b;
}
然后将返回的引用分配给原始变量:
b = bar(b);
关于java - 为什么在此代码中传递的引用不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26992171/