javastringobjectdata-conversionapache-commons-config

Apache Configuration add object instead of String


I have a problem with apache Configuration. Is it possible to add objects and not the string representation of them?

For example, I would like to save the whole 'SiteNode' and not the "toString()" variant:

public void persistSiteTree(Context context, Configuration config) {
    List<SiteNode> nodes = Model.getSingleton().getSession().getNodesInContextFromSiteTree(context);
    config.addProperty(CONFIG_PROPERTY_AUTHORISATION, nodes);
}

public void loadSiteTree(Context context, Configuration config) {
    List<Object> nodes = new ArrayList<>();
    nodes = config.getList(CONFIG_PROPERTY_AUTHORISATION, nodes);
    if(nodes != null && !nodes.isEmpty()) {
        // Load in sites tree
        SiteNode node = (SiteNode) nodes.get(0); // Gives error as String cannot be cast to "SiteNode"
    }
}

But when I call 'loadSiteTree' it gives me String cannot be case to SiteNode. Is it possible for Apache to save the object?


Solution

  • There are overloaded versions of getList() supporting a data type conversion to a specific target class.

    Have a look at the documentation.

    <T> List<T> getList(Class<T> cls, String key, List<T> defaultValue)

    Get a list of typed objects associated with the given configuration key returning the specified default value if the key doesn't map to an existing object.

    Something like this should work for you:

    List<SiteNode> nodes = config.getList(SiteNode.class,CONFIG_PROPERTY_AUTHORISATION, nodes);