Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java typecasting from extended

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>

like image 422
Twinone Avatar asked Jun 05 '26 11:06

Twinone


2 Answers

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.

like image 58
SLaks Avatar answered Jun 06 '26 23:06

SLaks


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.

like image 28
sp00m Avatar answered Jun 06 '26 23:06

sp00m