---
title: "Felix的一段涂鸦的代码"
author: "sswh"
date: "2014-08-18T14:53:03Z"
tags: []
categories: ["编程语言"]
slug: "felix"
draft: false
lastmod: "2014-08-18T14:58:44Z"
id: 2105532
url: "https://sswh.iteye.com/blog/2105532"
---

一段涂鸦代码：简易的Felix启动：

 

```
public static void main(String[] args) throws Exception {
	Map<String, String> properties = new HashMap<String, String>();
	// 仅仅调试用，为了在调试模块访问felix.framework包
	properties.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA,//
		"org.apache.felix.framework"// 
				+ ", org.apache.felix.framework.capabilityset"//
	);

	FrameworkFactory factory = new org.apache.felix.framework.FrameworkFactory();
	Framework framework = factory.newFramework(properties);
	// start之后，bundle-cache将会被还原，
	// 并按照bundle是否自动启动、bundle的startlevel以及框架的startlevel进行启动
	// 缓存的bundle不会触发install事件，但会触发start事件
	framework.start();

	// bundles目录下的是永远安装/启动的模块，即：不管模块是否上次在bundle-cache中已经卸载，重启后依然存在
	File[] files = new File("bundles").listFiles();
	List<File> installingFiles = Arrays.asList(files);
	// 排序的目的是保证在不同的环境下具有相同的执行效果；
	// 实践证明，同样的Windows XP系统，listFiles()的返回顺序不同
	// bundle的安装顺序，决定了bundle的id大小，
	// 而bundle.id大小对于package依赖的选取影响重大[当不同bundle导出了相同的package时] 
	Collections.sort(installingFiles);
	List<Bundle> installedBundles = new ArrayList<Bundle>(installingFiles.size());
	for (File file : installingFiles) {
		Bundle bundle = framework.getBundleContext().installBundle(file.toURI().toURL().toString());
		installedBundles.add(bundle);
	}

	for (Bundle bundle : installedBundles) {
		// 不仅启动模块，同时设置为autostart/autostop状态（即：由框架活动startlevel决定）
		bundle.start();
	}

	// 更改后续安装的bundle的缺省startlevel为核心模块缺省startlevel + 100
}
```

 

观察系统中已注册的所有服务：

```
@Validate
void start() throws Exception {
	Bundle bundle = FrameworkUtil.getBundle(getClass());
	BundleContext context = bundle.getBundleContext();

	Felix felix = (Felix) context.getBundle(Constants.SYSTEM_BUNDLE_LOCATION);
	Field field = Felix.class.getDeclaredField("m_registry");
	field.setAccessible(true);
	ServiceRegistry registry = (ServiceRegistry) field.get(felix);
	List<ServiceReference> refs = registry.getServiceReferences(null, null);
	Collections.sort(refs);
	Collections.reverse(refs);

	for (ServiceReference ref : refs) {
		System.out.println(ref + " in " + ref.getBundle());
		for (String key : ref.getPropertyKeys()) {
			Object value = ref.getProperty(key);
			if (value != null && value.getClass().isArray()) {
				value = Arrays.toString((Object[]) value);
			}
			System.out.println(key + " : " + value);
		}
		System.out.println();
	}
}
```