这个 NullPointerException 是否指 getFoos 返回 null 或者从 Collection 到 ArrayList 的转换存在问题?
为什么此行会导致 NullPointerException
:
List<Foo> foos = new ArrayList<Foo>(userDetailsService.getFoos(currentUser));
getFoos
方法仅返回 Foo
的 Collection
:
public Collection<Foo> getFoos(final String username)
我可以'判断 NullPointerException
是否引用 getFoos
返回 null
或从 Collection
到 Collection
的转换出现问题代码>ArrayList。
Why does this line cause a NullPointerException
:
List<Foo> foos = new ArrayList<Foo>(userDetailsService.getFoos(currentUser));
The getFoos
method simply returns a Collection
of Foo
s:
public Collection<Foo> getFoos(final String username)
I can't tell if the NullPointerException
refers to getFoos
returning null
or some problem with the cast from a Collection
to an ArrayList
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
取决于堆栈跟踪。前往第一行。如果它指向
java.util.ArrayList.
,则getFoos()
返回null
。或者,如果它指向问题中的特定行,则userDetailsService
为null
。Depends on the stacktrace. Head to the first line. If it points to
java.util.ArrayList.<init>
, thengetFoos()
has returnednull
. Or if it points to the particular line in your question, thenuserDetailsService
isnull
.这就是为什么我们有德墨忒尔法则。如果将连接在一起的两个语句分开,解决问题的运气会更好。
但是,很明显,返回的 null 集合(不是空集合)是导致该问题的原因。毕竟,使用空集合调用 ArrayList 构造函数不会导致空指针异常。
编辑:
我的错。 ArrayList 构造函数将尝试复制集合。所以空集合会导致空指针异常。我坚持最初的建议,将这两个语句脱钩。按以下方式编码将有助于更快地识别问题:
And that's why we have the Law of Demeter. If you separate the two statements that have been conjoined together, you would have better luck in resolving the issue.
However, it should be apparent that a null collection (not an empty collection) is returned which is responsible for the issue. After all, invoking the ArrayList constructor with a null collection will not result in a null pointer exception.
EDIT:
My bad. The ArrayList constructor will attempt to copy the collection. So a null collection can cause a null pointer exception. I stick to my original recommendation of decoupling the two statements. Coding in the following manner will help identify the issue faster:
失败的类型转换不会给您一个 NullPointerException 异常。
对
null
进行类型转换根本不会引发异常。因此,
getFoo
返回null
的理论是合理的。但也可能是userDetailsService
为null
或 NPE 被抛出到getFoo
中。您应该能够通过仔细阅读堆栈跟踪来区分这些情况...您没有将其包含在问题中(tsk,tsk)。
A failed typecast cannot give you a
NullPointerException
.Typecasting a
null
will not throw an exception at all.Therefore the theory that
getFoo
is returning anull
is plausible. But it could also be thatuserDetailsService
isnull
or that the NPE is thrown ingetFoo
.You should be able to distinguish these cases by carefully reading the stacktrace ... which you didn't include in your question (tsk, tsk).