【问题标题】:How to load Class in an OSGI E4 Environment while using Shiro?使用 Shiro 时如何在 OSGI E4 环境中加载类?
【发布时间】:2013-12-18 08:35:19
【问题描述】:

我正在尝试使用 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 named

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

【问题讨论】:

    标签: java osgi shiro e4


    【解决方案1】:

    如果您查看 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

    它尝试的第一件事是在附加到线程的 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);
    }
    

    【讨论】:

    • +1 另外请报告针对 Shiro 的错误。库不应在没有 Classloader 的情况下按名称加载类,因为这在模块化环境中总是失败。
    • 真的很好!经过 1 周的研究,你救了我!!非常感谢!你可以为 Shiro 报告一个错误吗?也许它有助于修复它。
    • (由没有足够代表离开 cmets 的新成员发布) @TomNelson 写道:我遇到了同样的问题,有类似的解决方法,所以我报告了issues.apache.org/jira/browse/SHIRO-537
    猜你喜欢
    • 2016-08-05
    • 2012-06-16
    • 1970-01-01
    • 2018-08-13
    • 2010-11-19
    • 2015-07-12
    • 2012-10-16
    • 2012-06-01
    • 1970-01-01
    相关资源
    最近更新 更多