我有以下代码:
public void Or(BinaryMap source, RectangleC area, Point at) {
Combine(source, area, at, new CombineFunction() {
@Override
public void combine(int[] target, int[] srcVector) {
for (int i = 0; i < target.length; ++i)
target[i] |= srcVector[i];
}
});
}
我无法理解接口(interface) CombineFunction
实现是如何工作的以及传递给函数组合的参数保存在哪里?
注意:
该代码不是我的,而是来自此处的引用 https://www.programcreek.com/java-api-examples/index.php?source_dir=SecugenPlugin-master/src/sourceafis/simple/Fingerprint.java#
我只是想了解它是如何工作的。
代码:
interface CombineFunction {
void combine(int[] target, int[] source);
}
void Combine(final BinaryMap source, final RectangleC area, final Point at,
final CombineFunction function) {
final int shift = (area.X & WordMask) - (at.X & WordMask);
int vectorSize = (area.Width >> WordShift) + 2;
CombineLocals combineLocals = new CombineLocals();
combineLocals.Vector = new int[vectorSize];
combineLocals.SrcVector = new int[vectorSize];
ParallelForDelegate<CombineLocals> delegate = new ParallelForDelegate<CombineLocals>() {
@Override
public CombineLocals delegate(int y, CombineLocals locals) {
LoadLine(locals.Vector, new Point(at.X, at.Y + y), area.Width);
source.LoadLine(locals.SrcVector,
new Point(area.X, area.Y + y), area.Width);
if (shift >= 0)
ShiftLeft(locals.SrcVector, shift);
else
ShiftRight(locals.SrcVector, -shift);
function.combine(locals.Vector, locals.SrcVector);
SaveLine(locals.Vector, new Point(at.X, at.Y + y), area.Width);
return locals;
}
@Override
public CombineLocals combineResults(CombineLocals result1,
CombineLocals result2) {
return null;
}
};
Parallel.For(0, area.Height, delegate, combineLocals);
}
最佳答案
假设 Combine
是具有以下签名的方法:
private void Combine(BinaryMap bm, RectangleC rc, Point p, CombineFunction cf)
注意:正如 Lutz Horn 在他的评论中指出的那样,方法名称应该以小写字母开头,因此应该是 combine
语法
写作
public void Or(BinaryMap source, RectangleC area, Point at) {
Combine(source, area, at, new CombineFunction() {
@Override
public void combine(int[] target, int[] srcVector) {
for (int i = 0; i < target.length; ++i)
target[i] |= srcVector[i];
}
});
}
与书写相同
class MyCombineFunction implements CombineFunction {
@Override
public void combine(int[] target, int[] srcVector) {
for (int i = 0; i < target.length; ++i)
target[i] |= srcVector[i];
}
}
然后以这种方式使用此类:
public void Or(BinaryMap source, RectangleC area, Point at) {
Combine(source, area, at, new MyCombineFunction());
}
这只是一个快捷方式,因此您不必声明新类。
如何在Combine方法中使用它
然后,Combine
方法使用您传递给它的 MyCombineFunction
的自定义实现。
它将在执行过程中以某种方式调用其 combine
方法,如下所示:
private void Combine(BinaryMap bm, RectangleC rc, Point p, CombineFunction cf) {
int[] target = ...;
int[] src = ...
cf.combine(target, source); // this will use the implementation you wrote when overriding the combine method
}
关于java - java 迭代匿名内部类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49770268/