向下转发Superclass到子类传递instanceof但遇到ClassCastException

时间:2018-04-25 11:12:34

标签: java spring-security casting downcast

我有两个对象,User和CustomUserDetails,它们扩展了User并实现了org.springframework.security.core.userdetails.UserDetails;

在我的存储库层中,我调用内存数据库并检索用户。

public User findByUsername(String username) {
    CustomUserDetails customUserDetails = new CustomUserDetails();
    User user = em.createQuery("from User where username = :username", User.class)
            .setParameter("username", username).getSingleResult();

    System.out.println(user.toString());

    if(customUserDetails instanceof User) {
        System.out.println("CustomUserDetails instance of User");
        customUserDetails = (CustomUserDetails) user;
        return customUserDetails;
    } else {
        System.out.println("CustomUserDetails is not instance of User");
        throw new ClassCastException();
    }
}

这是我的控制台输出

ID: 1, USERNAME : joe.bloggs@example.com, PASSWORD: gojoe, LIST<ROLE>: ROLE_ADMIN
CustomUserDetails instance of User
java.lang.ClassCastException: model.User cannot be cast to model.CustomUserDetails

为什么我无法从User转发到CustomUserDetails,即使我已经通过了instanceof检查? UserDetails接口类是否妨碍我成功投射?

1 个答案:

答案 0 :(得分:1)

你正在尝试施展

customUserDetails = (CustomUserDetails) user;

但是用户不是该实例,用户是User的实例。尝试将一个getter添加到User类以获取CustomUserDetails或使用if(user instanceof CustomUserDetails){...