這是Java的一個問題。我有一個名爲IMyObjectPredicate
它實現了一個單一的測試方法的接口適用於輸入:傳遞匿名類
public interface IMyObjectPredicate {
boolean test(MyObject x);
}
我想什麼是能夠傳遞對象之間圍繞IMyObjectPredicate
一個實例,並有test
功能更新其引用到它傳遞給它的新對象的變量。例如,考慮一類利用這個斷言的:
public class Tester {
MyObject o;
IMyObjectPredicate myTestFunction;
int myThreshold;
public Tester(/*stuff*/) {
/*Code here which initialises the Tester instance and 'myThreshold'*/
myTestFunction = new IMyObjectPredicate() {
@Override
public boolean test(MyObject o) {
return (o.value() > myThreshold);
}
};
}
pubic boolean isGood() {
return myTestFunction.test(o);
}
}
我想是能夠執行測試對象的深克隆的原因,我不會進入這裏。但是想法是Tester
的克隆實例應該測試謂詞對其自己的值myThreshold
,而不是引用第一個實例的myThreshold
。但是如果我通過myTestFunction
到Tester
的新實例,我猜它仍然會引用第一個實例的myThreshold
值,而不是根據封閉類的引用動態計算myThreshold
。
如何才能完成IMyObjectPredicate
對象的通過,該對象的測試函數使用對新對象的字段的引用來傳遞給?
編輯: 一個複雜的因素是,在一般情況下,它不會被可能從Tester
對象內的字段重建myTestFunction
完全。 myTestFunction
可能會被程序的其他部分以與Tester
的其他字段不相關的方式覆蓋。如果需要的話,我可以犧牲這種功能,但我寧願不爲高雅着想。
我不希望這是可能的。但是如果它在構造函數中,你可以創建一個新的謂詞。 –
@LouisWasserman通常,在程序過程中'myTestFunction'將被改變。我希望能夠根據需要按需複製它。 – Myridium
「IMyObjectPredicate」的匿名impl有一個no-arg'test()'方法,但接口要求它採用'MyObject'參數...? –