【问题标题】:Bundle.loadClass() returns Class instance without fields or methodsBundle.loadClass() 返回没有字段或方法的 Class 实例
【发布时间】:2011-12-06 00:17:36
【问题描述】:

我想以编程方式创建一个 OSGi 框架,用它加载一个 Bundle 并从该 bundle 加载一个类。当我调用Bundle.loadClass() 时,我得到一个Class 实例,所有字段\方法\构造函数字段都设置为空。它只有一个名字。我无法访问任何公共方法等。我已经尝试过 Equinox 和 Felix,结果相同。

捆绑包的MANIFEST

Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Activator: org.osgitest.osgitest.Activator
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
Bundle-Name: OSGi Test
Bundle-SymbolicName: org.osgitest.osgitest
Bundle-Version: 1.0
Import-Package: org.osgi.framework
Export-Package: org.osgitest.osgitest.test

框架设置:

FrameworkFactory ff = new EquinoxFactory();
Map<String, String> config = new HashMap<String, String>(1);
config.put("org.osgi.framework.storage.clean", "onFirstInit");
Framework framework = ff.newFramework(config);
framework.init();
framework.start();

FrameworkFactory ff = new org.apache.felix.framework.FrameworkFactory();
Map<String, String> config = new HashMap<String, String>(1);
config.put("org.osgi.framework.storage.clean", "onFirstInit");
Framework framework = ff.newFramework(config);
framework.init();
framework.start();

捆绑加载:

Bundle testBundle = framework.getBundleContext().installBundle("file:C:\\org-osgitest-osgitest.jar");
testBundle.start();
Class<?> classOne = testBundle.loadClass("org.osgitest.osgitest.test.ClassOne");
Class<?> activator = testBundle.loadClass("org.osgitest.osgitest.Activator");

Activator Class 实例包含构造函数引用,但没有公共方法。它有public void start(BundleContext c)public void stop(BundleContext c)

如何加载正确的Class?我究竟做错了什么?感谢您的帮助。

【问题讨论】:

    标签: java osgi classloader equinox apache-felix


    【解决方案1】:

    Class 使用某种惰性初始化。 Class 实例只有在执行 getMethods 等之后才会被方法/字段填充。这就是为什么我在调试器中看不到任何东西的原因。

    我尝试调用public static void main(String[] args),但没有将我的String[] 转换为Object。所以它被解释为Object[],JVM 寻找带有签名(args[0].class, args[1].class, ... , args[n].class) 的方法。这就是我的方法没有找到的原因。

    【讨论】:

      【解决方案2】:

      由于捆绑包是一个 jar,您是否尝试过以正常的 -classpath 模式加载该类? OSGi 只是定义了类加载器。 VM 仍然负责从字节码创建 Class 对象。所以我看不到 OSGi 框架如何从 Class 对象中“剥离”成员。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-11-24
        • 2015-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-24
        • 2012-03-30
        相关资源
        最近更新 更多