Home » Java » How to get the value of a private static field of a class from another OSGi bundle?

How to get the value of a private static field of a class from another OSGi bundle?

Posted by: admin October 26, 2017 Leave a comment

Questions:

I’m inside MyBundle and I’d like to get the value of a static field LOGGER from AnotherClass defined in the following way inside AnotherBundle:

package org.example.anotherbundle.anotherpackage

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class AnotherClass {
    private static final Logger LOGGER = LoggerFactory.getLogger(AnotherClass.class);
    ...
}

I tried doing it like this:

import org.osgi.framework.Bundle;
import org.eclipse.core.runtime.Platform;
import java.lang.reflect.Field;
import org.example.anotherbundle.anotherpackage.AnotherClass;

...

Bundle bundle = Platform.getBundle("org.example.anotherbundle");
Class<?> clazz = bundle.loadClass(AnotherClass.class.getName());
Field logger_field = clazz.getDeclaredField("LOGGER");
Object logger = logger_field.get(null); <-- NullPointerException is thrown here, but why??

I’m wondering why the NullPointerException is thrown by the get(Object object) method in the last line. The java.lang.reflect.Field documentation says that this exception is thrown only when the specified object is null and the field is an instance field. But in this case it is a static field, so it’s OK to pass null to that method because it should ignore this argument anyway, right?

Answers: