Java Class New Instance newInstance(String className, Object... parameters)

Here you can find the source of newInstance(String className, Object... parameters)

Description

new Instance

License

LGPL

Declaration

public static Object newInstance(String className, Object... parameters) 

Method Source Code

//package com.java2s;
//License from project: LGPL 

import java.lang.reflect.*;

public class Main {
    public static Object newInstance(String className, Object... parameters) {
        try {/*from w w w  .j  a v a2 s .  c  o m*/
            Class<?> objClass = Class.forName(className);
            Constructor<?> constructor = getConstructor(objClass, parameters);

            if (constructor != null) {
                return constructor.newInstance(parameters);
            }
        } catch (Exception e) {
        }

        return null;
    }

    public static Constructor<?> getConstructor(Class<?> cls, Object... parameters) {
        Constructor<?> constructor = null;

        for (Constructor<?> classMethod : cls.getConstructors()) {
            Class<?>[] parametersType = classMethod.getParameterTypes();
            boolean match = false;

            if (parametersType.length == parameters.length) {
                match = true;
                for (int i = 0, length = parametersType.length; i < length; i++) {
                    if (parameters[i] != null) {
                        if (!parametersType[i].isAssignableFrom(parameters[i].getClass())) {
                            match = false;
                            break;
                        }
                    }
                }
            }

            if (match) {
                constructor = classMethod;
                break;
            }
        }
        return constructor;
    }
}

Related

  1. newInstance(String className, Class castTo)
  2. newInstance(String className, Class[] parmsCls, Object[] parms)
  3. newInstance(String className, Object arg1)
  4. newInstance(String className, Object... args)
  5. newInstance(String className, Object... args)
  6. newInstance(String className, Object... params)
  7. newInstance(String className, Object[] args)
  8. newInstance(String className, Object[] args)
  9. newInstance(String className, Object[] args)