The Java Program: Create.java

  1 // Create.java -- create an instance of a class by name as string
  2 
  3 import java.io.File;
  4 import java.net.URL;
  5 import java.net.URLClassLoader;
  6 import java.net.MalformedURLException;
  7 
  8 public class Create {
  9 
 10    public static void main (String[] args) {
 11       final String dir = args.length>0?args[0]:null;
 12       final String cs = args.length>1?args[1]:"java.lang.String";
 13       try {
 14          System.out.println (System.getProperty ("java.class.path"));
 15          System.out.println ("Trying to create class for name:  " + cs);
 16          Class c;
 17          if (dir==null) {
 18             c = Class.forName (cs);
 19          } else {
 20             final File f = new File (dir);
 21             final URLClassLoader l = new URLClassLoader (new URL[] {f.toURL()});
 22             c = l.loadClass (cs);
 23          }
 24          System.out.println ("Class name:  " + c.getName());
 25          Object i = c.newInstance();
 26       } catch (MalformedURLException e) {
 27          System.out.println ("Malformed URL exception.");
 28       } catch (InstantiationException e) {
 29          System.out.println ("Instantiation exception.");
 30       } catch (IllegalAccessException e) {
 31          System.out.println ("Illegal access exception.");
 32       } catch (ClassNotFoundException e) {
 33          System.out.println ("Class not found exception.");
 34       } catch (NoSuchMethodError e) {
 35             // class must have a void () constructor
 36          System.out.println ("No such method error.");
 37       }
 38   }
 39 }
 40