如何从另一个OSGi包中获取类的私有静态字段的值?

时间:2017-10-26 12:46:37

标签: java reflection eclipse-plugin osgi

我在MyBundle内,我希望从LOGGER中获取AnotherClass的静态字段值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);
    ...
}

我尝试这样做:

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??

我想知道为什么最后一行NullPointerException方法引发了get(Object object)java.lang.reflect.Field文档说明只有当指定的对象为null并且该字段是实例字段时才会抛出此异常。但是在这种情况下它是一个静态字段,所以将null传递给该方法是可以的,因为它应该忽略这个参数,对吗?

0 个答案:

没有答案