Koch Curve Dynamic Class Loading

Since the view cannot directly access any class in the model, it must send a "message" to the model asking for a class to be loaded when the user wants to change what Koch factory is being used. For simplicity's sake, let assume that a drop-list exists in the view that holds the fully qualified class name of the desired factory (i.e. includes the package). When the user selects a factory from the drop-list, the string which holds the class name is sent to the model.

In the model, the appropriate class corresponding to the string must be loaded and the appropriate constructor called. This is accomplished using Java's dynamic class loading capability plus its "reflection" capability. "Reflection" is the ability to look a the structure of a class at run time, in this case, to find out how many input parameters are required for the constructor.

Below is a method that changes the current factory being used, given a String containing the name of the requested file:

	// Assume the existence of "aFactory", the current factory in use.
        public void changeFactoryTo(String s) {
            try {
		// get the first constructor of class "s":
                java.lang.reflect.Constructor c =  Class.forName(s).getConstructors()[0];
		// get an array of arrays of input parameters.
		// Here, arrays for zero and one input parameter: 
                Object[][] args = new Object[][]{new Object[]{}, new Object[]{aFactory}};
		// create a new instance given the number of input parameters for constructor:
                aFactory = (AFactory)c.newInstance(args[c.getParameterTypes().length]);
            }
            catch(Exception ex) {
               System.out.println(ex);
            }
        }