I have some static final String fields and I want to get their values using reflection so I made a method like this:
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;
}
I simply don't understand why I always receive NPE when trying to return the value:
return f.get(null) != null? f.get(null).toString() : "";
Exception is:
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)
Any clue?
Print the field before accessing it. I suspect you're trying to access a non-static field, and passing null to field.get() is thus not acceptable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With