Java examples for Reflection:Class
instantiate a class without throwing a exception
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Main{ public static void main(String[] argv) throws Exception{ Class clazz = String.class; System.out.println(instantiateClass(clazz)); }//from w w w .java 2 s .c o m /** * instantiate a class without throwing a exception * * @param <T> * @param clazz * @return * @throws WrappedRuntimeException */ public static <T> T instantiateClass(final Class<T> clazz) throws WrappedRuntimeException { try { T result = clazz.newInstance(); return result; } catch (Exception e) { throw new WrappedRuntimeException(e); } } @SuppressWarnings("unchecked") public static <T> T instantiateClass(final String clazzName) throws WrappedRuntimeException { Class<T> clazz; try { clazz = (Class<T>) Class.forName(clazzName); } catch (ClassNotFoundException e) { throw new WrappedRuntimeException(e); } return instantiateClass(clazz); } }