简体   繁体   English

如何用Java 8编写instanceof?

[英]How to write instanceof with Java 8?

I am new in Java 8 Optional. 我是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 . 我想根据user的实例创建一个不同的ResponseEntity。 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. 但是,如果可以,请避免使用instanceof运算符。 Add a isAdmin method to your User class : in class Admin , it would return true and in class NormalUser , it would return false . 向您的User类添加一个isAdmin方法:在类Admin ,它将返回true ,在类NormalUser ,它将返回false

The way you did it. 你这样做的方式。 However, you will have to cast u to the type you want. 但是,您必须将u为所需的类型。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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