如何呈现对象数组,如另一个对象的数组

时间:2012-11-07 15:36:38

标签: java

我有

class ForeighObject {...}
void someMethod(Object[]) {...}

ForeighObject[] fobjects = SomeStorage.getObjects();

我只能操作fobjects,所以我不能改变ForeighObjectsomeMethod的结构。如何覆盖ForeighObject.toString(例如)将其传递给someMethod而不复制元素?我是否可以创建一些可以“呈现”ForeighObject以仅覆盖一个方法的适配器类?

1 个答案:

答案 0 :(得分:1)

我不太清楚你的意思,但我猜someMethod对它给定的对象数组的元素调用toString

如果是这种情况,那么您可以使用包含预期fobjects方法的ForeighObject的包装子类来包装toString的每个元素。

e.g。

//Subclass which wraps a ForeighObject instance..
class ForeighObjectWrapper extends ForeighObject {
    ForeighObject wrapped;
    ForeighObjectWrapper(ForeighObject toWrap){
       super(/* get values from toWrap */);
        this.wrapped = toWrap;
    }
    //Add the custom behaviour..
    public String toString(){
         return "Some custom behaviour: " + wrapped.toString();
    }
}

ForeighObject[] fobjects = SomeStorage.getObjects();  //as before..
ForeighObject[] fobjectsWrapped = new ForeighObject[fobjects.length];
for(ForeighObject ob : fObjects){
    fobjectsWrapped.add(new ForeighObjectWrapper(ob));
}

//then call someMethod on fobjectsWrapped instead of fobjects..
someMethod(fobjectsWrapped); //will invoke custom behaviour..

请注意,如果someMethod还依赖于包装实例的其他方法/属性的行为,那么您需要覆盖这些方法,以便它们按预期工作。