简体   繁体   中英

How to write instanceof with Java 8?

I am new in Java 8 Optional. I have to change the following code :

@RequestMapping(value = "/account",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<UserDTO> getAccount() {
    return 
        Optional.ofNullable(userService.getUserWithAuthorities())
        .map(user -> 
            new ResponseEntity<>(
                new UserDTO(
                    user.getLogin(),
                    null,
                    user.getFirstName(),
                    user.getLastName(),
                    user.getEmail(),
                    "",
                    user.getLangKey(),
                    user.getAuthorities()
                        .stream()
                        .map(Authority::getName)
                        .collect(Collectors.toList())
                ),
                HttpStatus.OK
            )
        )
        .orElse(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));
}

I want to create a different ResponseEntity according to the instance of user . How i can write the equivalent of the following code:

if(user instanceof Admin )
{
// my logic
}
else if(user instanceof NormalUser)
{
// my logic
}

Thanks

You would do it like this :

@RequestMapping(value = "/account",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<UserDTO> getAccount() {
        return Optional.ofNullable(userService.getUserWithAuthorities())
            .map(user -> {
                if (user instanceof Admin) {
                    //...
                }
                return new ResponseEntity<>(new UserDTO(...), HttpStatus.OK);
            })
            .orElse(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));
    }

However, if you can, avoid the instanceof operator. Add a isAdmin method to your User class : in class Admin , it would return true and in class NormalUser , it would return false .

The way you did it. However, you will have to cast u to the type you want.

if (u instanceof Admin) {
    Admin a = (Admin) u;
    // your logic
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM