0

我有

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

ForeighObject[] fobjects = SomeStorage.getObjects();

我只能用 fobjects 操作,所以我既不能改变也不ForeighObject改变someMethod. 如何覆盖ForeighObject.toString(例如)将其传递给someMethod不复制元素?我可以创建一些可以“呈现”ForeighObject以仅覆盖一种方法的适配器类吗?

4

1 回答 1

1

我不太确定你的意思,但我猜这someMethod会调用toString它给定的对象数组的元素。

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

例如

//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 还依赖于包装实例的其他方法/属性的行为,那么您需要覆盖这些方法,以便它们按预期工作。

于 2012-11-07T15:51:05.937 回答