/** * Creates a new instance of the given class. It will use the default constructor if it is presents. * Otherwise it will try to use {@link sun.misc.Unsafe#allocateInstance(Class)} to create the instance. * @param clz Class of object to be instantiated. * @param <T> Type of the class * @return An instance of type {@code <T>} */ @SuppressWarnings("unchecked") public static <T> T newInstance(Class<T> clz) { try { try { Constructor<T> cons = clz.getDeclaredConstructor(); if (!cons.isAccessible()) { cons.setAccessible(true); } return cons.newInstance(); } catch (Exception e) { // Try to use Unsafe Preconditions.checkState(UNSAFE != null, "Fail to instantiate with Unsafe."); return unsafeCreate(clz); } } catch (Exception e) { throw Throwables.propagate(e); } }
/** * Creates a new instance of the given class. It will use the default constructor if it is presents. * Otherwise it will try to use {@link sun.misc.Unsafe#allocateInstance(Class)} to create the instance. * @param clz Class of object to be instantiated. * @param <T> Type of the class * @return An instance of type {@code <T>} */ @SuppressWarnings("unchecked") public static <T> T newInstance(Class<T> clz) { try { try { Constructor<T> cons = clz.getDeclaredConstructor(); if (!cons.isAccessible()) { cons.setAccessible(true); } return cons.newInstance(); } catch (Exception e) { // Try to use Unsafe Preconditions.checkState(UNSAFE != null, "Fail to instantiate with Unsafe."); return unsafeCreate(clz); } } catch (Exception e) { throw Throwables.propagate(e); } }