Dynamically load classes in Groovy from yaml parameter

Requires groovy 2.4.7 and snakeyaml 1.17 in classpath
References:

  1. http://tutorials.jenkov.com/java-reflection/dynamic-class-loading-reloading.html
  2. https://dzone.com/articles/class-loading-fun-groovy

The project:

├── config.yaml
├── snakeyaml-1.17.jar
└── src
    └── eu
        └── christophburmeister
            └── playground
                ├── Configuration.groovy
                ├── greeter
                │   ├── EnglishGreeter.groovy
                │   ├── FrenchGreeter.groovy
                │   ├── HebrewGreeter.groovy
                │   └── IGreeter.groovy
                ├── Main.groovy
                └── YamlConfiguration.groovy
---
greeterClass: FrenchGreeter
package eu.christophburmeister.playground.groovy

import eu.christophburmeister.playground.YamlConfiguration
import eu.christophburmeister.playground.greeter.IGreeter

class Main {
    private final static GREETERS_PACKAGE = 'eu.christophburmeister.playground.greeter'

    public static void main(String[] args){

        YamlConfiguration yamlConfiguration = new YamlConfiguration()
        yamlConfiguration.load()

        String greeterClass = yamlConfiguration.configuration.greeterClass
        IGreeter greeter

        try {
            def className = Class.forName("${GREETERS_PACKAGE}.${greeterClass}")
            greeter = className.newInstance()
        } catch  (ClassNotFoundException e) {
            e.printStackTrace();
        }
        greeter.greet()
    }
}
package eu.christophburmeister.playground

class Configuration {
    String greeterClass
}
package eu.christophburmeister.playground

import org.yaml.snakeyaml.Yaml

class YamlConfiguration {

    Configuration configuration

    void load() {
        configuration = new Configuration()
        Yaml yaml = new Yaml()

        try {

            // Parse the YAML file and return the output as a series of Maps and Lists
            def yamlMap = yaml.load(new FileInputStream('config.yaml'));
            yamlMap.each { key, value ->
                if (key == 'greeterClass'){
                    configuration.greeterClass = value
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package eu.christophburmeister.playground.greeter

interface IGreeter {
    void greet()
}
package eu.christophburmeister.playground.greeter

public class EnglishGreeter implements IGreeter{

    @Override
    void greet() {
        System.out.println('Hello')
    }
}
package eu.christophburmeister.playground.greeter

public class FrenchGreeter implements IGreeter{

    @Override
    void greet() {
        System.out.println('Bonjour')
    }
}
package eu.christophburmeister.playground.greeter

public class HebrewGreeter implements IGreeter{

    @Override
    void greet() {
        System.out.println('Shalom')
    }
}