简体   繁体   English

java中的对象引用

[英]Object reference in java

consider this simple servlet sample: 考虑这个简单的servlet示例:

protected void doGet(HttpServletRequest request, HttpServletResponse response){
    Cookie cookie = request.getCookie();
    // do weird stuff with cookie object
}

I always wonder.. if you modify the object cookie , is it by object or by reference? 我总是想知道..如果你修改对象cookie ,是按对象还是通过引用?

if you modify the object cookie , is it by object or by reference? 如果您修改对象cookie ,是按对象还是按引用?

Depends on what you mean by "modify" here. 取决于你在这里“修改”的意思。 If you change the value of the reference, ie cookie = someOtherObject , then the original object itself isn't modified; 如果更改引用的值,即cookie = someOtherObject ,则原始对象本身不会被修改; it's just that you lost your reference to it. 只是你失去了对它的引用。 However, if you change the state of the object, eg by calling cookie.setSomeProperty(otherValue) , then you are of course modifying the object itself. 但是,如果您更改对象的状态,例如通过调用cookie.setSomeProperty(otherValue) ,那么您当然正在修改对象本身。

Take a look at these previous related questions for more information: 有关更多信息,请查看以前的相关问题:

Java methods get passed an object reference by value . Java方法按值传递对象引用 So if you change the reference itself, eg 因此,如果您更改参考本身,例如

cookie = new MySpecialCookie();

it will not be seen by the method caller. 方法调用者不会看到它。 However when you operate on the reference to change the data the object contains: 但是,当您操作引用以更改对象包含的数据时:

cookie.setValue("foo");

then those changes will be visible to the caller. 然后调用者可以看到这些更改。

object reference is different from object. 对象引用不同于对象。 for eg: 例如:

class Shape
{
    int x = 200;
}

class Shape1
{
    public static void main(String arg[])
    {
        Shape s = new Shape();   //creating object by using new operator
        System.out.println(s.x);
        Shape s1;                //creating object reference
        s1 = s;                  //assigning object to reference
        System.out.println(s1.x);
    }
}

In the following line of code 在以下代码行中

Cookie cookie = request.getCookie(); /* (1) */

the request.getCookie() method is passing a refrence to a Cookie object. request.getCookie()方法将refrence传递给Cookie对象。

If you later on change cookie by doing something like 如果你以后cookie by做类似的事情改变cookie by

cookie = foo_bar(); /* (2) */

Then you are changing the internal refrence. 然后你正在改变内部参考。 It in no way affects your original cookie object in (1) 它决不会影响(1)中的原始cookie对象

If however you change cookie by doing something like 但是,如果您通过执行类似的操作来更改cookie

cookie.setFoo( bar ); /* assuming setFoo changes an instance variable of cookie */

Then you are changing the original object recieved in (1) 然后你要更改收到的原始对象(1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM