+
+ /**
+ * Create an empty object of the given type.
+ *
+ * @param type
+ * the object type (its class name)
+ *
+ * @return the new object
+ *
+ * @throws NoSuchMethodException if the given class is not compatible with this code
+ * @throws ClassNotFoundException if the class cannot be found or created
+ */
+ public static Object createObject(String type) throws NoSuchMethodException,
+ ClassNotFoundException {
+
+ try {
+ Class<?> clazz = getClass(type);
+ if (clazz == null) {
+ throw new ClassNotFoundException("Class not found: " + type);
+ }
+
+ String className = clazz.getName();
+ Object[] args = null;
+ Constructor<?> ctor = null;
+ if (className.contains("$")) {
+ Object javaParent = createObject(className.substring(0,
+ className.lastIndexOf('$')));
+ args = new Object[] { javaParent };
+ ctor = clazz.getDeclaredConstructor(new Class[] { javaParent
+ .getClass() });
+ } else {
+ args = new Object[] {};
+ ctor = clazz.getDeclaredConstructor();
+ }
+
+ ctor.setAccessible(true);
+ return ctor.newInstance(args);
+ } catch (NoSuchMethodException e) {
+ throw new NoSuchMethodException(
+ String.format(
+ "Objects of type \"%s\" cannot be created by this code: maybe the class"
+ + " or its enclosing class doesn't have an empty constructor?",
+ type));
+
+ }
+ catch (SecurityException e) { throw new ClassNotFoundException("Cannot instantiate: " + type, e); }
+ catch (InstantiationException e) { throw new ClassNotFoundException("Cannot instantiate: " + type, e); }
+ catch (IllegalAccessException e) { throw new ClassNotFoundException("Cannot instantiate: " + type, e); }
+ catch (IllegalArgumentException e) { throw new ClassNotFoundException("Cannot instantiate: " + type, e); }
+ catch (InvocationTargetException e) { throw new ClassNotFoundException("Cannot instantiate: " + type, e); }
+ }