Eclipse - 如何生成Getters和Setter不考虑"按引用"

Sex*_*yMF 0 java pass-by-reference

如果java总是通过引用传递变量,为什么eclipse会在没有任何考虑的情况下生成bean.

代替: return myStr;

需要是 return new String(myStr);

没有?

编辑
确定,我的例子很糟糕.
让我们离开eclipse,当我想要返回一个Custom对象时.我是否需要创建一个"复制构造函数"并将其返回,如下所示:

return new MyCustomObject(myCustomObject);


class MyCustomObject{

  private String str; 
  public MyCustomObject(String str){
    this.str = str;
  }

  public MyCustomObject(MyCustomObject obj){
    this.str =  obj.str;    
  }
}
Run Code Online (Sandbox Code Playgroud)

我必须写那个吗?

Cam*_*ner 5

没有.

在Java中,每个对象变量都是一个引用.对象不能通过值传递,只有基元可以(并且始终是).嗯,这有点误导.该基准是按值传递,但你能想到的一切作为参考,只要不是在C++的观点.

也许最容易使用一个例子.

SomeObject foo;

public void doSomething(SomeObject bar) {
    bar.whatever();
    bar = new SomeObject();
    bar.someOtherMethod();
}

public void doStuff() {
    foo = new SomeObject();
    doSomething(foo);
}
Run Code Online (Sandbox Code Playgroud)

所以,foo是对实例的引用SomeObject.当doSomething被调用时,该参考值被复制到bar,所以现在foobar是相同的标记SomeObject.

该行bar.whatever()调用引用whatever的同一对象foo.

bar = new SomeObject()意味着foobar现在参阅不同 SomeObject的情况下,这样someOtherMethod称为该物体上foo指.

这与C++完全不同,其中

void doSomething(SomeObject& bar) {
    bar = whatever;
}
Run Code Online (Sandbox Code Playgroud)

有一个完全不同的意思.你真的不应该用C++术语来思考Java.

关于你的例子,Strings在Java中是不可变的,所以即使对象可以通过值传递没关系.

关于你的第二个例子,如果你想返回一个调用者不能用来污染你的内部状态的对象,那么,是的,你需要有一个拷贝构造函数(或类似的东西).

例如:

class ClassWithInternalList {
    private List<String> reallyImportantData;

    public List<String> getImmutableViewOfData() {
        // Take advantage of the java.util.Collections tool for making a List immutable.
        return Collections.unmodifiableList(reallyImportantData);
    }

    public List<String> getSafeCopyOfData() {
        // Return a copy that the caller can modify without changing reallyImportantData.
        return new ArrayList<String>(reallyImportantData);
    }

    public List<String> justGetTheData() {
        // Return a reference to reallyImportantData that the caller can modify at will.
        return reallyImportantData;
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以根据具体情况选择适当类型的返回值(正常引用,不可变视图或副本).根据您的具体操作,三个选项中的任何一个或全部都可能是合适的.

java.util.Collections可以很容易地获得a的不可变视图Collection,但对于自定义类,您需要自己进行不可变的操作.

请记住,如果存在可变性问题,您只需要执行此操作.你的MyCustomObject例子仍然是不可变的(因为调用者不能改变返回MyCustomObject实例中的任何状态),所以问题仍然没有实际意义.