java - 制作适用于不同对象类型的功能接口(interface)

标签 java

我为我的项目定义了一个名为 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/

相关文章:

java - 从字符串中提取和删除实体

java - 使用定时服务每 n 个月安排一次任务

tomcat 服务器上的 javax.net.ssl.SSLHandshakeException

java - REST - POST 到资源集合和 If-Match header 时的 ETag

java - Tomcat 8 - context.xml 在数据源中使用环境变量

javascript - 关闭 FireFox 中的身份验证提示

java - 在 Maven 配置文件中设置系统变量

java - eclipse 火星 : no option to create new server

java - 多个 GWT 页面之间的公共(public)文件

java - 使用安卓 getIdentifier()