import java.util.*; public class Reflect { // Illustrates Bloch Item 53 // Sample usage: // java Reflect java.util.HashSet dog cat ant bat // java Reflect java.util.TreeSet dog cat ant bat // Reflective instantiation with interface access // Bulky (vs calling a constructor), with possible runtime errors public static void main (String [] args) { // Translate the class name into a Class object Class cl = null; // note that try/catch block interrupts declaration try{ cl = Class.forName (args[0]); } catch (ClassNotFoundException e) { // runtime, not compile time, error System.err.println("Class not found."); System.exit(1); // terminates JVM! generally bad practice // ok for command line utility } // Instantiate the class Set s = null; try{ s = (Set) cl.newInstance(); } catch (IllegalAccessException e) { // runtime, not compile time, error System.err.println("Class not accessible."); System.exit(1); } catch (InstantiationException e) { // runtime, not compile time, error System.err.println("Class not instantiable."); System.exit(1); } // Exercise the set s.addAll(Arrays.asList(args).subList(1, args.length)); System.out.println(s); } }