mercredi 2 novembre 2016

Java Reflection to map Properties to Object

i got the following source code to map the properties file to my Object.

    private Configuration MapPropertiesToObjectOrNull(Properties defaultProps){

    Configuration config = new Configuration();
    Enumeration e = defaultProps.propertyNames();

    while (e.hasMoreElements()) {
        String key = (String) e.nextElement();
        try {
            Field currField = config.getClass().getDeclaredField(key);
            try {
                currField.set(config, defaultProps.getProperty(key) );
            } catch (IllegalAccessException e1) {
                e1.printStackTrace();
            }
        } catch (NoSuchFieldException e1) {
            e1.printStackTrace();
        }

    }

    return config;

}

Is this a good "mapping approach" to avoid hardcoded "Key"-String in my source code? You maybe have some other ideas?





Aucun commentaire:

Enregistrer un commentaire