我有
class ForeighObject {...}
void someMethod(Object[]) {...}
和
ForeighObject[] fobjects = SomeStorage.getObjects();
我只能操作fobjects,所以我不能改变ForeighObject
和someMethod
的结构。如何覆盖ForeighObject.toString
(例如)将其传递给someMethod
而不复制元素?我是否可以创建一些可以“呈现”ForeighObject
以仅覆盖一个方法的适配器类?
答案 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还依赖于包装实例的其他方法/属性的行为,那么您需要覆盖这些方法,以便它们按预期工作。