Here you can find the source of newInstance(Class> cls, Map
@SuppressWarnings("unchecked") static <T> T newInstance(Class<?> cls, Map<Class<?>, Constructor<?>> cache)
//package com.java2s; //License from project: Apache License import java.lang.reflect.Constructor; import java.util.Map; public class Main { @SuppressWarnings("unchecked") static <T> T newInstance(Class<?> cls, Map<Class<?>, Constructor<?>> cache) { final Constructor ctor = getDefaultConstructor(cls, cache); try {// w w w. jav a2s. c o m return (T) ctor.newInstance(); } catch (Throwable t) { throw new RuntimeException("Failed to instantiate " + cls.getName(), t); } } static Constructor<?> getDefaultConstructor(Class<?> cls, Map<Class<?>, Constructor<?>> cache) { if (cache != null) { Constructor ctor = cache.get(cls); if (ctor != null) return ctor; } final Constructor[] constructorArray = cls.getDeclaredConstructors(); Constructor constructor = null; for (Constructor ct : constructorArray) { if (ct.getParameterTypes() != null && ct.getParameterTypes().length != 0) continue; constructor = ct; if (constructor.getGenericParameterTypes().length == 0) break; } if (constructor == null) throw new IllegalStateException("No default constructor found for " + cls.getName()); constructor.setAccessible(true); if (cache != null) cache.put(cls, constructor); return constructor; } }