Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this method using reflections throws npe?

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?

like image 959
Cristian Boariu Avatar asked Feb 20 '26 03:02

Cristian Boariu


1 Answers

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.

like image 175
JB Nizet Avatar answered Feb 21 '26 23:02

JB Nizet