将超类向下转换为子类通过 instanceof 但遇到 ClassCastException
Downcasting Superclass to Subclass passes instanceof but encounters ClassCastException
我有两个对象,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
为什么我已经通过了 instanceof 检查,却无法从 User 向下转换为 CustomUserDetails? UserDetails 接口 class 是否妨碍我成功投射?
您正在尝试投射
customUserDetails = (CustomUserDetails) user;
但是用户不是那个的实例,用户是用户的实例。尝试向用户 class 添加 getter 以获取 CustomUserDetails 或使用 if(user instanceof CustomUserDetails){...
我有两个对象,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
为什么我已经通过了 instanceof 检查,却无法从 User 向下转换为 CustomUserDetails? UserDetails 接口 class 是否妨碍我成功投射?
您正在尝试投射
customUserDetails = (CustomUserDetails) user;
但是用户不是那个的实例,用户是用户的实例。尝试向用户 class 添加 getter 以获取 CustomUserDetails 或使用 if(user instanceof CustomUserDetails){...