【问题标题】:Replace own instance inside a java object在java对象中替换自己的实例
【发布时间】:2011-06-27 17:06:41
【问题描述】:

在我的例子中,实现者应该能够“更新”一个对象。

//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"); 

但是,在 Class 内部,我还没有弄清楚如何一次替换所有属性。这种方法行不通,但也许还有其他机会解决它:

    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();
}

【问题讨论】:

    标签: java instance instance-variables


    【解决方案1】:

    你不能替换'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...
    }
    

    【讨论】:

    • 这意味着:this.setId(response.getId()), this.setName(response.getName())... 30 次以上只是为了这个类
    • 顺便说一下,我从原始类生成了一个接口并将其应用于包装器。所以,包装器看起来像原来的类。
    【解决方案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;
        ...
    

    但是,通过这样的优化,您必须注意字段的浅拷贝是适当的。

    【讨论】:

      猜你喜欢
      • 2012-07-07
      • 2014-03-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-13
      • 2017-12-22
      • 2014-05-30
      • 1970-01-01
      • 2010-11-23
      相关资源
      最近更新 更多