gpt4 book ai didi

java - 为什么 IntelliJ 告诉我在这种情况下引用不能为空?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:24:38 26 4
gpt4 key购买 nike

这是我的代码:

private void foo(Bar bar) {
Session session = null;
Class entityClazz = null;
try {
entityClazz = Hibernate.getClass(bar);
if (bar != null) {

并且 IntelliJ 会警告我上面最后一条语句的消息:

Condition 'bar != null' is always 'true'. This inspection analyzes method control and data flow to report possible conditions that are always true or false, expressions whose value is statically proven to be constant, and situations that can lead to nullability contract violations.

当我删除语句时:

entityClazz = Hibernate.getClass(bar);

警告将消失。

这里 IntelliJ 的想法是什么,是什么阻止了 bar 为 null?

最佳答案

根据 hibernate 文档,这是 org.hibernate.Hibernate 类中的 getClass() 方法所做的。

public static Class getClass(Object proxy) {
if ( proxy instanceof HibernateProxy ) {
return ( ( HibernateProxy ) proxy ).getHibernateLazyInitializer()
.getImplementation()
.getClass();
}
else {
return proxy.getClass();
}
}

根据文档,在空参数的情况下抛出 HibernateException,它是 NetableRuntimeException 的扩展类,也是 RuntimeException

Intellij 能够分析这一点,使用它的代码检查很容易发现 loc

entityClazz = Hibernate.getClass(bar);

会抛出 NPE。如果它抛出 NPE,则永远不会达到 if 条件语句,因为 NestableRuntimeException 是未经检查的异常。

您可以将 if 条件放在 Hibernate.getClass(bar) 之上,这对于 null 安全方法来说是理想的。

希望一切顺利。

引用资料

Hibernate Documentation

Code Analysis - Intellij

Code Inspection - Intellij

关于java - 为什么 IntelliJ 告诉我在这种情况下引用不能为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36590881/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com