繁体   English   中英

不能直接从 Java 中的方法返回值,为什么?

[英]Can't return value directly from method in Java, why?

这将编译

 public ResponseEntity<User> getUserById(@PathVariable(value = "id") Long userId) throws UserNotFoundException {
        ResponseEntity u = userRepository.findById(userId)
                .map(p->ResponseEntity.ok(new UserResource(p)))
                .orElseThrow(() -> new UserNotFoundException(userId));
        return u;
    }

但这不会

 public ResponseEntity<User> getUserById(@PathVariable(value = "id") Long userId) throws UserNotFoundException {
        return userRepository.findById(userId)
                .map(p->ResponseEntity.ok(new UserResource(p)))
                .orElseThrow(() -> new UserNotFoundException(userId));
    }

怎么来的?

第一个代码片段返回ResponseEntity<UserResource>的实例,然后将其分配给原始类型变量。 然后将原始类型变量返回到泛型类型的变量(应该会产生警告)。 如果任何代码到达错误类型的 ResponseEntity 字段,它将在运行时引发异常。 所以第一个代码可以编译,因为编译器允许将原始类型变量分配给泛型,反之亦然。

第二个代码片段不使用原始类型,因此完成了泛型类型兼容性检查(通常在编译时进行,因为泛型类型由于擦除而在运行时不存在) - 因此它无法正确编译。

暂无
暂无

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

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