1

我正在尝试使用 E4 和他的 OSGi(Equinox) 环境构建桌面应用程序。对于我的用户安全,我正在使用 Shiro。但我可以从我的 OSGi 加载类,但 shiro 不能!

在我的捆绑包中,我尝试了这个:

初始化激活器.java:

public class InitActivator implements BundleActivator {
private static BundleContext context;

static BundleContext getContext() {
    return context;
}

@Override
public void start(BundleContext context) throws Exception {

    //1. OSGi loadClass function
    System.err.println(context.getBundle().loadClass("com.firm.demo.MyCustomClass")
                    .getName());
    //2. Using Apache Shiro ClassUtils
    System.err.println("Shiro : " + ClassUtils.forName("com.firm.demo.MyCustomClass"));

    }

 }

1. system.err用他的限定名返回正确的类。2.system.err返回一个org.apache.shiro.util.UnknownClassException: Unable to load class named

我如何在 OSGi 中使用 Shiro 来查找具有名称的类?

4

1 回答 1

2

如果您查看 ClassUtils 的源代码,您将看到它如何尝试加载类: http://grepcode.com/file/repo1.maven.org/maven2/org.apache.shiro/shiro-core/1.0 。 0-孵化/org/apache/shiro/util/ClassUtils.java#ClassUtils.forName%28java.lang.String%29

它尝试的第一件事是在附加到线程的 ClassLoader 的帮助下加载类。如果失败,它会尝试使用加载 ClassUtils 的 ClassLoader 进行加载。如果失败,它会尝试使用系统 ClassLoader 加载类。

你可以欺骗第一个,线程上下文类加载器。我必须提到,这只是一种解决方法,而不是在 OSGi 世界中很好的解决方案:

BundleWiring bundleWiring = context.getBundle().adapt(BundleWiring.class);
ClassLoader bundleClassLoader = bundleWiring.getClassLoader();
Thread currentThread = Thread.currentThread();

ClassLoader originalCl = currentThread.getContextClassLoader()
currentThread.setContectClassLoader(bundleClassLoader);
try {
    System.err.println("Shiro : " + ClassUtils.forName("com.firm.demo.MyCustomClass"));
} finally {
    currentThread.setContextClassLoader(originalCl);
}
于 2013-12-18T09:25:47.347 回答