public ClassAsFactory(Class<T> kind) { try { x = kind.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } }
public static void main(String[] args) { Class c = null; try { c = Class.forName("typeinfo.toys.FancyToy"); } catch (ClassNotFoundException e) { print("Can't find FancyToy"); System.exit(1); } printInfo(c); for (Class face : c.getInterfaces()) printInfo(face); Class up = c.getSuperclass(); Object obj = null; try { // Requires default constructor in order to // create a super or Toy object: obj = up.newInstance(); } catch (InstantiationException e) { print("Cannot instantiate"); System.exit(1); } catch (IllegalAccessException i) { print("Cannot access"); System.exit(1); } printInfo(obj.getClass()); }
// Classtoken version: public static <T> void fill(Addable<T> addable, Class<? extends T> classToken, int size) { for (int i = 0; i < size; i++) try { addable.add(classToken.newInstance()); } catch (Exception e) { throw new RuntimeException(e); } }