[英]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.