ReflectionUtil getField 抛出 NullPointerException
我使用一个类,通过 FilterCriterionList (某种查找器)进行 Hibernate 查询,直到现在它一直运行良好并触发 NullPointerException,我完全不知道为什么会触发它。
这是使用以下值触发空指针的方法(在 ReflectionUtil 中)(请注意,向其抛出的其他值工作正常,只是这些值似乎给出了错误):
type = interface java.util.List
fieldName =参数
首先它抛出 NoSuchFieldException 并在第二次运行时(因为它在 field = getField(type.getSuperclass(), fieldName); 处再次调用)使其抛出 NullPointerException 并且停止死亡(所有这些都发生在我的 UnitTest 中,而不是实时环境还)。
public static Field getField(Class type, String fieldName) {
Field field = null;
try {
field = type.getDeclaredField(fieldName);
} catch (Exception e) {
if (!type.equals(Object.class)) {
field = getField(type.getSuperclass(), fieldName);
}
}
return field;
}
关于为什么会发生这种情况的任何想法(或者我可以做些什么来解决它?)。我无法真正展示更多代码,因为它非常复杂并且是公司代码。
I use a class that makes my Hibernate Query through a FilterCriterionList (sort of finder) and it's always worked perfectly until now and triggers a NullPointerException and I have absolutely no idea as to why it's triggered.
This is the method (in ReflectionUtil) that triggers the nullpointer with the following values (mind you that the other values thrown at it work perfectly and it's just these that seem to give an error):
type = interface java.util.List
fieldName = parameter
First it throws the NoSuchFieldException and on it's second run (as it's called again at field = getField(type.getSuperclass(), fieldName);) makes it throw a NullPointerException and just stop dead (all of this happens in my UnitTest, not a live environment yet).
public static Field getField(Class type, String fieldName) {
Field field = null;
try {
field = type.getDeclaredField(fieldName);
} catch (Exception e) {
if (!type.equals(Object.class)) {
field = getField(type.getSuperclass(), fieldName);
}
}
return field;
}
Any ideas as to why this happens (or what I can do to fix it?). I can't really show off more code as it's quite complicated and it's company code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
java.util.List
是一个接口,因此对其调用getSuperclass()
会导致null
。递归应用
getField()
的正确方法如下:java.util.List
is an interface, therefore callinggetSuperclass()
on it results innull
.The correct way to apply
getField()
recursively is the following:您这样调用:
它永远不会起作用,因为 List 是一个接口,并且它没有任何称为参数的字段。对于第二次调用,其为 null,因为接口 List 没有超类。
You called like this:
It would have never worked as List is an interface and it doesen't have any field called parameter. For the second call, its' null because interface List doesnet have a superclass.
来自 Class.getSuperclass 文档
From the Class.getSuperclass documentation