I have the following code:
public static <T extends User> void addUser(String username,
String passwordHash, Class<T> userClass, File usersDir) {
T user = (T) new User(username, passwordHash);
UserManager.toFile(user, usersDir);
}
Eclipse gives me the following warning:
Type safety: Unchecked cast from User to T
Why do I get the warning that it's not checked if i defined T to extend User with <T extends User>
You're misunderstanding generics.
T extends User doesn't mean that T is User; it means that T can be any class that inherits User.
If T is FunkyUser, your code won't work.
T can be any extending class of User. You're instantiating a new User, i.e. the super class. So, if T isn't exactly the User type (i.e. a subclass), the cast is unsafe and a ClassCastException will be thrown.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With