一种获取OSGi任意Bundle的ClassLoader的方法

在OSGi环境中,在Bundle内部代码中要得到自己Bundle的ClassLoader就很简单,在自己Bundle的代码中,直接写this.getClass().getClassLoader()就得到了自己Bundle的ClassLoader了。但怎么在其他Bundle或外部代码中得到任意一个Bundle的ClassLoader呢?Bundle和BundleContext都没有提供getClassLoader方法来获取,我就用了一种比较另类的方法来获取。突破口就在Bundle.loadClass(String className)方法,目前此方法已经在QuickWebFramework中应用了。

思路:

1.调用Bundle的findEntries方法,得到Bundle中任意一个class文件。

2.根据这个class文件的路径,得到类名

3.调用Bundle的loadClass方法,得到这个类

4.调用这个类的getClassLoader方法,得到ClassLoader

 PS:

1.由上面的思路可知此方法不能用于没有一个Java类的Bundle

2.OSGi系统Bundle(即ID为0的Bundle)得不到class文件,所以此方法不能用于OSGi系统Bundle

代码如下:

 

import java.net.URL;
import java.util.Enumeration;

import org.osgi.framework.Bundle;

/**
 * 插件辅助类
 * 作者博客:http://www.cnblogs.com/aaaSoft
 * @author aaa
 * 
 */
public class BundleUtils {
    /**
     * 得到Bundle的类加载器
     * 
     * @param bundle
     * @return
     */
    public static ClassLoader getBundleClassLoader(Bundle bundle) {
        // 搜索Bundle中所有的class文件
        Enumeration<URL> classFileEntries = bundle.findEntries("/", "*.class",
                true);
        if (classFileEntries == null || !classFileEntries.hasMoreElements()) {
            throw new RuntimeException(String.format("Bundle[%s]中没有一个Java类!",
                    bundle.getSymbolicName()));
        }
        // 得到其中的一个类文件的URL
        URL url = classFileEntries.nextElement();
        // 得到路径信息
        String bundleOneClassName = url.getPath();
        // 将"/"替换为".",得到类名称
        bundleOneClassName = bundleOneClassName.replace("/", ".").substring(0,
                bundleOneClassName.lastIndexOf("."));
        // 如果类名以"."开头,则移除这个点
        while (bundleOneClassName.startsWith(".")) {
            bundleOneClassName = bundleOneClassName.substring(1);
        }
        Class<?> bundleOneClass = null;
        try {
            // 让Bundle加载这个类
            bundleOneClass = bundle.loadClass(bundleOneClassName);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        // 得到Bundle的ClassLoader
        return bundleOneClass.getClassLoader();
    }
}

 

转载于:https://www.cnblogs.com/aaaSoft/archive/2013/01/30/2883008.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值