---
title: "common-configuration中CompositeConfiguration类的一个需要注意的地方"
author: "JetMah"
date: "2010-07-29T15:57:39Z"
tags: []
categories: ["编程语言"]
slug: "common-configuration-compositeconfiguration"
draft: false
lastmod: "2010-07-29T15:57:39Z"
id: 724466
url: "https://jetma.iteye.com/blog/724466"
---

原文出处: [http://www.javatang.com/archives/2010/07/29/0513435.html](http://www.javatang.com/archives/2010/07/29/0513435.html)  
作者: Jet Mah from [Java堂](http://www.javatang.com/)  
声明: **可以非商业性任意转载, 转载时请务必以超链接形式标明文章原始出处、作者信息及此声明！**

 

在[Common-Configuration](http://commons.apache.org/configuration/)中，CompositeConfiguration类用来对多个配置文件进行组合处理，该类有一个getNumberOfConfigurations()方法，用来读取Configuration对象的个数，但是如果执行下面的代码：

1. CompositeConfiguration config = new CompositeConfiguration();
2. int number = config.getNumberOfConfigurations();
3. System.out.println(number);

这个时候会发现number的值是1而不是0，虽然没有向其中添加任何Configuration对象。CompositeConfiguration构造方法的代码如下：

01. public CompositeConfiguration()
02. {
03. clear();
04. }
05. public void clear()
06. {
07. configList.clear();
08. // recreate the in memory configuration
09. inMemoryConfiguration = new BaseConfiguration();
10. ((BaseConfiguration) inMemoryConfiguration).setThrowExceptionOnMissing(isThrowExceptionOnMissing());
11. ((BaseConfiguration) inMemoryConfiguration).setListDelimiter(getListDelimiter());
12. ((BaseConfiguration) inMemoryConfiguration).setDelimiterParsingDisabled(isDelimiterParsingDisabled());
13. configList.add(inMemoryConfiguration);
14. }

可以看到默认构造方法中调用了clear()方法，而clear方法中自动添加了一个BaseConfiguration对象，该对象用于存放自身的一些配置信息。所以这个时候的数量是1而不是0，这一点容易让人迷惑。

 

 

参考资料：  
[Re: \[Configuration\] CompositeConfiguration.getNumberOfConfigurations( ) question](http://permalink.gmane.org/gmane.comp.jakarta.commons.user/10923)