Here you can find the source of newInstance(Class extends Object> cl, Object[] args)
cl
from constructor with arguments args
, even if the constructor is a private constructor.
public static Object newInstance(Class<? extends Object> cl, Object[] args) throws Exception
//package com.java2s; import java.lang.reflect.Constructor; import java.util.HashMap; import java.util.Map; public class Main { private static Map<Class<?>, Class<?>> builtInMap = new HashMap<Class<?>, Class<?>>(); /**/*from w w w.j a va 2 s. c o m*/ * Create an instance of a class <code>cl</code> from constructor with * arguments <code>args</code>, even if the constructor is a private constructor. * When looking for the constructor, arguments which can be converted to primitives * are searched as primitives.<br> * For example, if args types are {String,Integer), the following constructor is searched: * constructor(String,int). */ public static Object newInstance(Class<? extends Object> cl, Object[] args) throws Exception { Class<? extends Object>[] classArray = new Class<?>[args == null ? 0 : args.length]; for (int i = 0; i < args.length; i++) { classArray[i] = builtInMap.get(args[i].getClass()) == null ? args[i].getClass() : builtInMap.get(args[i].getClass()); } Constructor<? extends Object> constructor = cl.getDeclaredConstructor(classArray); constructor.setAccessible(true); return constructor.newInstance(args); } }