How to write instanceof with Java 8?
18,298
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
.
Author by
Pracede
Java,J2EE, Spring, Spring, Hibernate,AngularJS, Javascript, Jquery, Bootstrap,NodeJS, MongoDB, Express
Updated on June 09, 2022Comments
-
Pracede almost 2 years
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