在我的例子中,实现者应该能够“更新”一个对象。
//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();
}
最佳答案
你不能替换'this',你可以替换this的内容(字段),或者用另一个替换对this的引用...
替换“this”引用的一种方法是使用包装器:
SameClassWrapper myObject = new SameClassWrapper(SameClass.find(123,params));
myObject.update(params);
方法 SameClassWrapper.update 类似于
{
sameClass = code to build the new SameClass instance...
}
关于java - 替换java对象中自己的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5005881/