我为我的项目定义了一个名为 Function
的函数接口(interface)。它只有一个方法,call
,如下所示:
public interface Function {
public void call();
}
在我的 Field 对象中,我有这个:
public class Field {
private Square[][] matrix; //Square is dispensable.
public Field(int rows, int cols) {
matrix = new Square[rows][cols];
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
this.matrix = new Square(i * Square.NORMAL_WIDTH, j * Square.NORMAL_HEIGHT);
}
}
}
}
它工作得很好,并且类似于 JavaScript,但我无法将我的注意力对象传递给它。但考虑到我想开发这个方法:
public void each(Function f){
int rows = matrix.length;
for(int i = 0; i < rows; i++){
int cols = matrix[i].length;
for(int j = 0; j < cols; j++){
f.call();
}
}
}
它将把特定的代码片段(在本例中为函数实现)附加到矩阵的每个元素。这样,我就可以访问它的属性。 但矩阵的每个对象都是一个正方形。我怎样才能访问它?我可以将它传递给函数,
//making an small alteration to the parameter.
public interface Function {
public void call(Square square);
}
public void each(Function f){
int rows = matrix.length;
for(int i = 0; i < rows; i++){
int cols = matrix[i].length;
for(int j = 0; j < cols; j++){
f.call(matrix[i][j]);
}
}
}
但是,我仍然会被困在 Square
类型中。也许我可以使用泛型类型?
最佳答案
是的,您需要使其通用。
最简单的情况:
public interface Function<T> {
public void call(T arg);
}
public void each(Function<Square> f) { ... }
更好的做法是声明 each()
如下:
public void each(Function<? super Square> f) { ... }
这样您不仅可以申请Function<Square>
,也是一个Function
其任何父类(super class)型,例如
Function<Object> PRINT = new Function<Object>() {
public void call(Object arg) {
System.out.println(arg);
}
}
关于java - 制作适用于不同对象类型的功能接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17241344/