The Java Program: Construct.java

  1 import java.lang.reflect.Constructor;
  2 import java.lang.reflect.InvocationTargetException;
  3 import java.io.ObjectOutputStream;
  4 import java.io.FileOutputStream;
  5 import java.io.IOException;
  6 
  7 class Construct {
  8    Construct (Class c) {
  9       Constructor con = null;
 10       // Get the constructor that takes no arguments

 11       try {
 12          con = c.getConstructor(new Class[] {});
 13       } catch (NoSuchMethodException e) {
 14          System.out.println("No constructor that takes no arguments.");
 15          return;
 16       }
 17       // Another way of getting the constructor with no arguments

 18       boolean found = false;
 19       Constructor[] cons = c.getConstructors();
 20       for (int i=0; i<cons.length && !found; i++) {
 21          if (cons[i].getParameterTypes().length == 0) {
 22             con = cons[i];
 23             found = true;
 24          }
 25       }
 26       if (!found) {
 27          System.out.println("No constructor that takes no arguments.");
 28          return;
 29       }
 30         
 31       Object obj = null;
 32       try {
 33          obj = con.newInstance(new Object[] {});
 34       } catch (InvocationTargetException e) {
 35          e.getTargetException().printStackTrace();
 36          return;
 37       } catch (InstantiationException e) {
 38          System.out.println("Abstract classes or interfaces cannot be instantiated.");
 39          return;
 40       } catch (IllegalAccessException e) {
 41          System.out.println("Constructor is private or protected.");
 42          return;
 43       }
 44         
 45       try {
 46          System.out.print(
 47             "Serializing " + con.getDeclaringClass().getName() +
 48              " to " + con.getName() + ".ser ... \n");
 49             
 50          ObjectOutputStream os = new ObjectOutputStream(
 51             new FileOutputStream(con.getName() + ".ser"));
 52          os.writeObject(obj);
 53          os.close();
 54       } catch (IOException e) {
 55          e.printStackTrace();
 56       }
 57    }
 58     
 59    public static void main(String[] args) {
 60       if (args.length != 1) {
 61          System.err.println("Usage: java Construct <classname>");
 62       } else {
 63          try {
 64             new Construct(Class.forName(args[0]));
 65          } catch (ClassNotFoundException e) {
 66             e.printStackTrace();
 67          }
 68       }
 69    }
 70 }