gpt4 book ai didi

java - 如何在使用 Shiro 时在 OSGI E4 环境中加载类?

转载 作者:行者123 更新时间:2023-11-30 04:06:16 25 4
gpt4 key购买 nike

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

在我的 bundle 中,我尝试这样做:

InitActivator.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 name

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

最佳答案

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

它尝试的第一件事是在附加到线程的类加载器的帮助下加载类。如果失败,它会尝试使用加载 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);
}

关于java - 如何在使用 Shiro 时在 OSGI E4 环境中加载类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20653146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com