如何用 Java 8 编写 instanceof?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28531305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write instanceof with Java 8?
提问by Pracede
I am new in Java 8 Optional. I have to change the following code :
我是 Java 8 Optional 的新手。我必须更改以下代码:
@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:
我想根据user
. 我如何编写等效于以下代码的代码:
if(user instanceof Admin )
{
// my logic
}
else if(user instanceof NormalUser)
{
// my logic
}
Thanks
谢谢
回答by Tunaki
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
.
但是,如果可以,请避开instanceof
运营商。isAdmin
向您的User
类添加一个方法:在类中Admin
,它会返回,true
而在类中NormalUser
,它会返回false
。
回答by bb94
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
}