使用泛型类型实现接口

时间:2010-10-07 18:07:55

标签: 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?
    }
}

4 个答案:

答案 0 :(得分:10)

如果某行映射到用户,则该行应为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;
    }
}

答案 1 :(得分:3)

尝试

public class UserMapper implements RowMapper<User> {

答案 2 :(得分:3)

编译器对T一无所知。因此,它要求您将User投射到T。如果您只打算将T用作User的类型,则可以使用以下内容来限制泛型类型并为编译器提供更多信息。

public class UserMapper<T extends User> implements RowMapper<T>
...

如果您的代码实际上是这样的,那么您总是返回User并且它不依赖于T。因此,您应该只返回User而不是T

答案 3 :(得分:0)

因为T!=用户。

相关问题