使用泛型类型实现接口

Mar*_*enn 4 java generics

我正在尝试实现Spring的RowMapper接口,但是,我的IDE提示我将返回对象强制转换为"T",我不明白为什么.谁能解释我错过的东西?

public class UserMapper<T> implements RowMapper<T> {
    public T mapRow(ResultSet rs, int row) throws SQLException {
        User user = new User();
        user.firstName(rs.getInt("fname"));
        user.lastName(rs.getFloat("lname"));
        return user; // Why am I being prompted to cast this to "T", should this be fine?
    }
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*l D 10

如果一行映射到用户,那么它应该是a RowMapper<User>

即:


public class UserMapper implements RowMapper<User> {
    public User mapRow(ResultSet rs, int row) throws SQLException {
        User user = new User();
        user.firstName(rs.getInt("fname"));
        user.lastName(rs.getFloat("lname"));
        return user;
    }
}
Run Code Online (Sandbox Code Playgroud)