Commons Configuration AbstractConfiguration的get()和getArray()有什么问题?

时间:2018-11-22 12:03:10

标签: arrays properties-file apache-commons-config

使用commons-configuration2:2.4

my.properties

arrayOfSingle=0xA
arrayOfMultiples=0xD,0xA

CONFIG.getArray(int[].class, "arrayOfSingle"));

  org.apache.commons.configuration2.ex.ConversionException:
    The value '0xA' (class java.lang.String) can't be converted to a [I object

CONFIG.getArray(int[].class, "arrayOfMultiples"));

  org.apache.commons.configuration2.ex.ConversionException:
    The value '0xD,0xA' (class java.lang.String) can't be converted to a [I object

CONFIG.getArray(Integer[].class, "arrayOfSingle"));

  org.apache.commons.configuration2.ex.ConversionException: 
    The value '0xA' (class java.lang.String) can't be converted to a [Ljava.lang.Integer; object

CONFIG.getArray(Integer[].class, "arrayOfMultiples"));

  org.apache.commons.configuration2.ex.ConversionException:
    The value '0xD,0xA' (class java.lang.String) can't be converted to a [Ljava.lang.Integer; object

CONFIG.get(int[].class, "arrayOfSingle") // prints "[I@7dba7035", i.e.works

CONFIG.get(int[].class, "arrayOfMultiples")

  org.apache.commons.configuration2.ex.ConversionException:
    Could not convert 0xD,0xA to java.lang.Integer! Invalid hex number.

CONFIG.get(Integer[].class, "arrayOfSingle") // prints "[Ljava.lang.Integer;@44d379bb", i.e. works

CONFIG.get(Integer[].class, "arrayOfMultiples")

  org.apache.commons.configuration2.ex.ConversionException:
    Could not convert 0xD,0xA to java.lang.Integer! Invalid hex number.

getArray(Class<?> cls, String key, Object defaultValue)已过时(建议使用get(Class<T> cls, String key, T defaultValue)),但getArray(Class<?> cls, String key)无效,get(Class<T> cls, String key)也无效。

2 个答案:

答案 0 :(得分:1)

我希望这对于希望具有如下所示的逗号分隔属性并获取列表或值数组的人很有用。
甚至this都被接受,但是如果您不喜欢同一键的多个条目,则可以使用以下解决方案。

添加依赖项:

compile("org.apache.commons:commons-configuration2:2.7")

application.properties文件:

arrayOfMultiples=0xD,0xA

客户:

PropertiesConfiguration propertiesConfiguration = new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class)
        .configure(new Parameters()
                .properties()
                .setFileName("application.properties-file-path")
                .setListDelimiterHandler(new DefaultListDelimiterHandler(',')))
        .getConfiguration();

输出:

propertiesConfiguration.get(Integer[].class, "arrayOfMultiples");
// or
propertiesConfiguration.get(int[].class, "arrayOfMultiples"))

[13,10]

注意:由于值是十六进制的,因此转换器会将其转换为十进制。但是适用于任何int值。

在需要列表时也可用于以下类型的阅读

propertiesConfiguration.getList(int.class, "arrayOfMultiples");
// or
propertiesConfiguration.getList(Integer.class, "arrayOfMultiples");

答案 1 :(得分:0)

放弃getArray()并使用Lists and arrays中所述的多行变体。

my.properties

arrayOfMultiples=0xD
arrayOfMultiples=0xA

CONFIG.get(int[].class, "arrayOfMultiples")
CONFIG.get(Integer[].class, "arrayOfMultiples")