我有一些static final String
字段,我想使用反射来获取它们的值,所以我做了一个这样的方法:
public String getLogoSrc(final String provider) {
if (provider.equals(StringUtils.EMPTY)) {
return StringUtils.EMPTY;
}
logger.info("---provider is: "+provider);
for (Field f : ConstantsBean.class.getDeclaredFields()) {
f.setAccessible(true);
if (f.getName().contains(provider.toUpperCase().replace(" ", "_"))) {
try {
return f.get(null) != null? f.get(null).toString() : "";
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return StringUtils.EMPTY;
}
我根本不明白为什么我在尝试返回值时总是收到 NPE:
return f.get(null) != null? f.get(null).toString() : "";
例外是:
java.lang.NullPointerException
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl
.java:36)
at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccess
orImpl.java:18)
at java.lang.reflect.Field.get(Field.java:358)
at com.gravitant.cloud.common.jsf.core.beans.ConstantsBean.getLogoSrc(Co
nstantsBean.java:195)
有什么线索吗?