Friday, December 25, 2009

Generics and Class.forName

This post shows how you can create objects of a specified class, using a class name and the supertype of the class you are trying to create.
public final class BeanCreator {

  /**
   * Suppress constructor.
   */
  private BeanCreator(){
  }

  /**
   * Creates an object of the class name and supertype.
   * @param <T>
   * @param className
   * @param superType
   * @return
   * @throws ClassNotFoundException
   */
  public static <T> T create(final String className,
             final Class<T> superType) throws Exception {
    final Class< ? extends T> clazz =
         Class.forName(className).asSubclass(superType);
    return create(clazz);
  }

  /**
   * Creates an object of the specified class using
   * its public or private no-arg constructor.
   *
   * @param <T>
   * @param classToCreate
   * @return
   */
  public static <T> T create(final Class<T> classToCreate)
                                      throws Exception {
        final Constructor<T> constructor =
                   classToCreate.getDeclaredConstructor();
        if (constructor == null) {
         throw new Exception("Could not create a new "+
         "instance of the dest object: " + classToCreate
         + ".  Could not find a no-arg constructor.");
        }

        // If private, make it accessible
        if (!constructor.isAccessible()) {
            constructor.setAccessible(true);
        }
        return constructor.newInstance();
  }
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.