Java Class New Instance newInstance(Class cl, Object[] args)

Here you can find the source of newInstance(Class cl, Object[] args)

Description

Create an instance of a class cl from constructor with arguments args, even if the constructor is a private constructor.

License

Open Source License

Declaration

public static Object newInstance(Class<? extends Object> cl, Object[] args) throws Exception 

Method Source Code


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

Related

  1. newInstance(Class cls)
  2. newInstance(Class cmdClass)
  3. newInstance(Class constructorClass, Object[] parameters)
  4. newInstance(Class klass)
  5. newInstance(Class targetClass)
  6. newInstance(Class clazz)
  7. newInstance(Class componentType, int length)
  8. newInstance(Class classZ)
  9. newInstance(Class clazz)