4

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?
    }
}
3
  • 4
    How is the compiler supposed to know that T represents User? Perhaps you mean to implement the interface as implements RowMapper<User> instead? Commented Oct 7, 2010 at 18:10
  • I thought the compiler would know from the instantiation of the class, i.e. : new UserMapper<User>(); Commented Oct 7, 2010 at 18:16
  • 1
    But when you say the class is UserMapper<T>, you're saying that any type can be specified for a new instance of it. For example, new UserMapper<String>(). Yet the class will only ever return a User! Commented Oct 7, 2010 at 18:20

4 Answers 4

12

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

3

Try

public class UserMapper implements RowMapper<User> {

4 Comments

Why isn't it UserMapper<User>?
Because the generic only applies to RowMapper.
Because RowMapper wants to know the type, but UserMapper is only for that type. So UserMapper is telling RowMapper, "this is my type". But nobody else is allowed to tell UserMapper what its type is - it already knows it.
Here is how I often think of generics and translate something like UserMapper implements RowMapper<User> in my head: "UserMapper is a RowMapper of User"
3

The compiler does not know anything about T. Therefore, it is asking you to cast User to T. If you are only planning on using T as a type of User you can use the following to restrict the generic type and give the compiler more information.

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

If your code actually looks like that, you are always returning User and it is not dependent on T. Therefore you should just make the return type User and not T.

Comments

0

Because T != User.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.