3

I was reading through Spring in Action and found something like this could anyone explain how we have used RowMapper as an Anonymous class if it is an Interface as per RowMapper documentation.

 public Employee getEmployeeById(long id) {
      return jdbcTemplate.queryForObject(
          "select id, firstname, lastname, salary " +
          "from employee where id=?",
          new RowMapper<Employee>() {
            public Employee mapRow(ResultSet rs,
                    int rowNum) throws SQLException {
              Employee employee = new Employee();
              employee.setId(rs.getLong("id"));
              employee.setFirstName(rs.getString("firstname"));

              employee.setLastName(rs.getString("lastname"));
              employee.setSalary(rs.getBigDecimal("salary"));
              return employee;
            }
          },
          id);
    }
4

3 回答 3

4

匿名类new Something() {...}不是Something. 相反,Something. 因此,从接口派生匿名类是完全有效和有用的。

于 2013-08-30T13:32:04.890 回答
1

匿名类不是类的实例,而只是定义类的另一种方式,类似于嵌套类,但由于与方法相关,因此可重用性较低。由于您可以定义实现接口的类

public A implements B {

}

并且您可以引用该类的实例,声明为接口

B b = new A();

你也可以用匿名类来做到这一点。唯一要做和记住的(为此存在编译器)是您必须实现接口本身中定义的所有方法。

该解决方案是一种更简洁的方法:

public EmployeeController {

     public Employee getEmployeeById(long id) {
          return jdbcTemplate.queryForObject(
              "select id, firstname, lastname, salary " +
              "from employee where id=?",
              new CustomRowMapper(),
              id);
        }


   class CustomRowMapper implements RowMapper<Employee>() {
            public Employee mapRow(ResultSet rs, int rowNum) throws SQLException {
              Employee employee = new Employee();
              employee.setId(rs.getLong("id"));
              employee.setFirstName(rs.getString("firstname"));

              employee.setLastName(rs.getString("lastname"));
              employee.setSalary(rs.getBigDecimal("salary"));
              return employee;
            }
     }
}
于 2013-08-30T13:46:04.040 回答
0

语法

new SomeInterface() {
  // Definition for abstract methods
}

定义了一个匿名类。只要接口中指定的所有方法都在大括号内定义,这是一个实现给定接口的有效类。

请注意,此表达式隐式定义了一个匿名类该类的一个实例。

于 2013-08-30T13:31:55.157 回答