package net.dafydd.demo; /** * Dynamic loading example application.
* * MOTIVATION: Although Java looks like a simplified C++, dynamically loading code * is an example of a task that's easy in Java and comparatively difficult in C++. * This is a problem for C++ because it has low-level dependencies - meaning * that loading code at runtime is more involved and very platform dependent. * * FEATURES: * Loads first command-line argument, or if no first arg, loads foo.class * Invokes .toString() on loaded object, and then prints * out a list of the interfaces implemented by the class which was loaded. * NOTE: that references to "Class" are to java.lang.Class (because java.lang is * implicitly imported into every java file. * * @author Dafydd Rees * @version 2.0 */ public class LoadAndListInterface { /** A main function for the app. If no argument is supplied, * the function will try to load a class named foo. * If there are arguments, then an attempt to load the classname * specified by the first arugment is made. */ public static void main(String argv[]) { String cname; // name of class to load Class cnamecls; // the class object for cname's class int ifCount=0; // the number of interfaces implemented by cname's class if (argv.length>0) cname = argv[0]; // set up classname else cname = "foo"; try { // for Exceptions cnamecls = Class.forName(cname); // get the Class class for the cname Object o = cnamecls.newInstance(); // NOTE: using o below implicitly calls o.toString() // due to definition of println method System.out.println("Loaded "+cname+" and as a string is "+o+"."); ifCount =printInterfaces(cname); // Try to print out the interface names... System.out.println("Number of interfaces "+ifCount+"."); } catch (Throwable e) { // Potentially many conditions here: // ClassNotFoundException // InstantiationException // IllegalAccessException // Also a potential for NoSuchMethodError due to say nonexistence of // a 0-arg constructor. // we ignore the distinctions and just "bail out". System.out.println("Failed to load " + cname + "."); System.out.println("Because of "+e); } } /** Print out a list of the interfaces implemented a class. * The output is written on System.out. * @param cname the name of the class (as a string) from which the interfaces are to be listed. * @return the number of interfaces implemented. * @exception java.lang.ClassNotFoundException Thrown when the class represented by the * cname is not found. */ protected static int printInterfaces(String cname) throws ClassNotFoundException { int i; Class ifList[] ; // the array of class objects that represent each interface in cname ifList = ((Class.forName(cname)).getInterfaces()); System.out.println("Interfaces implemented:\n"); for (i=0; i