Java Spike: LoadAndListInterface
Dynamic loading example application.
Motivation
When you run a java application or applet, code is loaded into the Java virtual machine on demand. This isn't the case with most traditional systems such as C++ where the code from all the classes is linked together into one big binary lump. In Java, writing code that refers to a certain class name will cause the the virtual machine to try to load a class of that name through the default classloader at runtime. This means that you can write software that assembles parts of itself at runtime. Somehow it needs to know what class names to load, it needs to load them and establish that they implement interfaces that it knows how to use. Then it needs to create instances of those classes used. (The last stage is to cast the created objects to an appropriate interface and dispatch calls to those objects as normal - but this isn't demonstrated here.)
This spike demonstrates what you need to implement the ParameterClasses Java idiom.
Features
- Loads the class specified by the first command-line argument.
- If there are no command line arguments, it attempts to load "foo.class".
- The program instantiates an object from the specified class using the no argument constructor. (If the class loaded has no no argument constructor, the spike will throw a "java.lang.InstantiationException".)
- A list of the interfaces implemented by that class are discovered using reflection.
- The list of interfaces implemented by the class are printed out using "System.out".