2011-02-15 33 views
4

在我的情况下,实现者应该能够“更新”一个对象。在java对象内部替换自己的实例

//creating an instance (follows the active record pattern) 
    SameClass myObject = SameClass.find(123,params); 

//myObject gets replaced by the output of the web api inside, but it feels like an update for the implementator 
    myObject.update("ask the web api to paint it black"); 

但是,在类内我还没有想出如何一次性替换所有属性。这种方法是行不通的,但也许有一些其他的机会来解决这个问题:

public void update(String newParams) { 
//Can't replace "this" (that call returns an instance of "SameClass") 
     this = ConnectionFramework.getForObject(SameClass.class,"some url",newParams); 
    } 

的“ConnectionFramework”其实是Spring RestTemplate for Android。该版本的繁体字是:

public void update(HashMap<String,String> params) { 
SameClassResponse response = restTemplate.getForObject(ENDPOINT+"/{id}.json",SameClassResponse.class, params); 
    this = response.getSameClass(); 
} 

回答

4

不能取代“这个”,可以更换的这个内容(领域),或由另一个替换参考这个...

的一种方式,以取代在 '此' 参考是有一个包装:

SameClassWrapper myObject = new SameClassWrapper(SameClass.find(123,params)); 
myObject.update(params); 

方法SameClassWrapper.update会像

{ 
    sameClass = code to build the new SameClass instance... 
} 
+0

这将意味着:this.setId(response.getId()),this.setName(response.getName())...为此类提供了更多次数 – OneWorld 2011-02-15 15:56:54

2

您不能设置“this”引用。

既然你不能设置“this”引用,你能做的最好是取像这样

public void update(String newParams) { 
    //Can't replace "this" (that call returns an instance of "SameClass") 
    SameClass fetchedObject = ConnectionFramework.getForObject(SameClass.class,"some url",newParams); 

对象,然后将所有的“状态”之类的是更换

this.setValue1(fetchedObject.getValue1()); 
    this.setvalue2(fetchedObject.getValue2()); 
    ... 

优化是直接设置字段。

this.field1 = fetchedObject.field1; 
    this.field2 = fetchedObject.field2; 
    ... 

但是,通过这样的优化,您必须注意浅场复制是合适的。