Runtime Reflection using EditFrame

Since Factory/Java is itself written in Java, it can easily be used from within other Java classes. This means, that the generation process done by a factory can be invoked at runtime, and since Java supports dynamic class loading and reflective access to classes, the generated classes can be used straight away.

This example demonstrates how Factory/Java is already capable of runtime reflection that could be useful in hot-deployment enabled environments. It would enable components - be it GUI components or any other - to adapt dynamically to system changes, upgrades and extensions, providing a high degree of flexibility and tolerance.

The notion of generator-type-safety, which is being explored in the Factory/Java project, could statically ensure the dynamic safety of such adaptive components, because it would assure that no such adaption would bring the component into an erroneous state.

Source Code

The following Java class source can be found in factory/src/test/RTEditFrameTest.java in the Factory/Java .zip-archive. It reads in a classname from the keyboard and loads the corresponding class t. Then it creates an instance of factory EditFrame and uses its facture() method with t to generate a corrsponding GUI component class editFrame. This class is instantiated by means of the Java reflection API and the edit() method called on that instance with an instance of class t as argument.

package test;

import java.io.*;
import java.util.Vector;
import factory.Factory;
import java.lang.reflect.*;

class RTEditFrameTest {
    public static void main(String argv[]) {
        try {
            // get type parameter
            System.out.println("Please enter classname:");
            BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
            String cname = r.readLine();
            Class t = Class.forName(cname);
   
            // facture class
            Factory f = new Factory("examples/EditFrame");
            Vector params = new Vector();
            params.add(t);
            Class editFrame = f.facture(params);
                       
            // use class
            params = new Vector();
            params.add(t);
            Method edit = editFrame.getMethod("edit",
                (Class[]) params.toArray(new Class[0]));
            Object myEditFrame = editFrame.getConstructor(new Class[0])
                .newInstance(null);
            Object o = t.getConstructor(new Class[0]).newInstance(null);
            params = new Vector();
            params.add(o);
            edit.invoke(myEditFrame,params.toArray());
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

This class can be compiled in the factory directory with
javac -classpath classes -d classes src/test/RTEditFrameTest.java
and run with
java -classpath classes test.RTEditFrameTest