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();
  }
}

1 comment:

  1. Thanks for writing such a good article, I stumbled onto your blog and read a few post. I like your style of writing... SEO services

    ReplyDelete