Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing interface with generic type

Tags:

java

generics

I'm trying to implement Spring's RowMapper interface, however, my IDE is prompting me to cast the return object to "T" and I don't understand why. Can anyone explain what I'm missing?

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?
    }
}
like image 243
MarkPenn Avatar asked Dec 04 '22 11:12

MarkPenn


1 Answers

If a row maps to a User, then it should be a RowMapper<User>

ie:


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;
    }
}
like image 97
Michael D Avatar answered Dec 22 '22 10:12

Michael D