-1

I have two objects, User and CustomUserDetails which extends User and implements org.springframework.security.core.userdetails.UserDetails;

In my repository layer I make a call to my in-memory database and retrieve a user.

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();
    }
}

Here is my console output

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

Why I am unable to downcast from User to CustomUserDetails even though I have passed the instanceof check? Is UserDetails interface class getting in my way to successfully cast?

shirafuno
  • 387
  • 3
  • 9
  • 24
  • checkout this link https://stackoverflow.com/questions/7526817/use-of-instance-of-in-java – Mithat Konuk Apr 25 '18 at 11:17
  • You are checking the type of `customUserDetails` and then casting `user`. – Eran Apr 25 '18 at 11:17
  • 3
    Change `if(customUserDetails instanceof User)` to `if(user instanceof CustomUserDetails)` – Eran Apr 25 '18 at 11:18
  • `CustomUserDetails` is instance of `User`, but `User` is not instance of `CustomUserDetails ` in this particular case, that's why casting is not appropriate. – J-Alex Apr 25 '18 at 11:21
  • CustomerDetail reference just point customerdetail not user that because when you check instance of user is not going to work firstly you have make sure customerdetail reference point to user object – Mithat Konuk Apr 25 '18 at 11:25
  • Okay, thank you for pointing out I had things the wrong way around. If I would like a CustomUserDetails object from the User object, should I create a converter object in my service layer which create a CustomUserDetails object and maps each attribute from User to CustomUserDetails? – shirafuno Apr 25 '18 at 11:35

1 Answers1

1

You are trying to cast

customUserDetails = (CustomUserDetails) user;

but the user is not an instance of that, the user is an instance of User. Try adding a getter to the User class to get the CustomUserDetails or use a if(user instanceof CustomUserDetails){...

finman
  • 40
  • 6