-1

不知道这里发生了什么,我正在尝试做一些非常简单的事情,通过引用设置一个对象。我写了两次相同的代码,一次通过引用设置对象,一次返回新对象并将其设置在那里。这是代码

for (Person p : test) {
    bcPetDao.refreshRef(p.pet);
    Log.e("Woo1", "Name:" + p.pet);
    Log.e("Woo1", "Addess: " + p.pet.hashCode());
}
for (Person p : test) {
    p.pet = bcPetDao.refresh(p.pet);
}
Log.e("Woo2", "Name:" + test.get(0).pet);

refresh 和 refreshRef 的代码是:

public T refresh(T object) {
    try {
        String id = cachedClass.idEntry.getKey().get(object).toString();
        return queryOne(new Query(cachedClass.idColName + " = ?", new String[] { id }, null, null, null, null));
    } catch (IllegalArgumentException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

public void refreshRef(T object) {
    try {
        String id = cachedClass.idEntry.getKey().get(object).toString();
        object = queryOne(new Query(cachedClass.idColName + " = ?", new String[] { id }, null, null, null, null));
        BcLog.e("In Ref name is: " + object.toString());
        BcLog.e("Addess: " + object.hashCode());
    } catch (IllegalArgumentException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

Java 泛型有什么东西可以使它不只是工作吗?这是日志打印输出。

04-23 22:50:55.643: E/BcLog(30237): In Ref name is: ID: 119, name: 3fdb2a3ab1c0a2e8
04-23 22:50:55.643: E/BcLog(30237): Addess: 1090746752
04-23 22:50:55.643: E/Woo1(30237): Name:ID: 119, name: null
04-23 22:50:55.643: E/Woo1(30237): Addess: 1087524160
04-23 22:50:55.663: E/BcLog(30237): In Ref name is: ID: 118, name: 3fccb118500e0f1c
04-23 22:50:55.663: E/BcLog(30237): Addess: 1088206960
04-23 22:50:55.663: E/Woo1(30237): Name:ID: 118, name: null
04-23 22:50:55.663: E/Woo1(30237): Addess: 1087682616
04-23 22:50:55.684: E/BcLog(30237): In Ref name is: ID: 117, name: 3fe026bb4d24bfe2
04-23 22:50:55.684: E/BcLog(30237): Addess: 1088359352
04-23 22:50:55.684: E/Woo1(30237): Name:ID: 117, name: null
04-23 22:50:55.684: E/Woo1(30237): Addess: 1090724368
04-23 22:50:55.714: E/BcLog(30237): In Ref name is: ID: 116, name: 3fe26d6a3967d838
04-23 22:50:55.714: E/BcLog(30237): Addess: 1090659992
04-23 22:50:55.714: E/Woo1(30237): Name:ID: 116, name: null
04-23 22:50:55.714: E/Woo1(30237): Addess: 1088417312
04-23 22:50:55.734: E/BcLog(30237): In Ref name is: ID: 115, name: 3fef8ec496c0cdb2
04-23 22:50:55.734: E/BcLog(30237): Addess: 1088221128
04-23 22:50:55.744: E/Woo1(30237): Name:ID: 115, name: null
04-23 22:50:55.744: E/Woo1(30237): Addess: 1088572064
04-23 22:50:55.824: E/Woo2(30237): Name:ID: 119, name: 3fdb2a3ab1c0a2e8
4

1 回答 1

2

Java 是按值传递的。当您调用refreshRef( object )时,该方法将拥有对象引用的本地副本(将其视为指针),因此在方法主体内分配此引用不会影响您传入的对象。

由于内存中只有一个对象副本,因此您可以更改引用的对象的成员,但不能更改实例本身。

于 2013-04-24T04:09:18.410 回答