Java Class New Instance newInstance(final String className, final Object[] args)

Here you can find the source of newInstance(final String className, final Object[] args)

Description

Creates a new instance of the given class by passing the given arguments to the constructor.

License

Open Source License

Parameter

Parameter Description
className Name of class to be created.
args Constructor arguments.

Return

New instance of given class.

Declaration

public static Object newInstance(final String className, final Object[] args) 

Method Source Code

//package com.java2s;
/*//from  www. j a  v a2  s.co m
 * Copyright 2010 The JA-SIG Collaborative. All rights reserved. See license
 * distributed with this file and available online at
 * http://www.ja-sig.org/products/cas/overview/license/index.html
 */

public class Main {
    /**
     * Creates a new instance of the given class by passing the given arguments
     * to the constructor.
     * @param className Name of class to be created.
     * @param args Constructor arguments.
     * @return New instance of given class.
     */
    public static Object newInstance(final String className, final Object[] args) {
        try {
            return newInstance(Class.forName(className), args);
        } catch (final ClassNotFoundException e) {
            throw new IllegalArgumentException(className + " not found");
        }
    }

    /**
     * Creates a new instance of the given class by passing the given arguments
     * to the constructor.
     * @param clazz Class of instance to be created.
     * @param args Constructor arguments.
     * @return New instance of given class.
     */
    public static Object newInstance(final Class clazz, final Object[] args) {
        final Class[] argClasses = new Class[args.length];
        for (int i = 0; i < args.length; i++) {
            argClasses[i] = args[i].getClass();
        }
        try {
            return clazz.getConstructor(argClasses).newInstance(args);
        } catch (final Exception e) {
            throw new IllegalArgumentException("Error creating new instance of " + clazz, e);
        }
    }
}

Related

  1. newInstance(final Class clazz)
  2. newInstance(final Class type, final int length)
  3. newInstance(final ClassLoader classLoader, final String className, final Object... constructorArgs)
  4. newInstance(final Object obj, final String clazz)
  5. newInstance(final String className, ClassLoader cl)
  6. newInstance(final String fullyQualifiedClass)
  7. newInstance(Map> providerMap, String provider, Class[] paramsClass, Object[] paramValues)
  8. newInstance(Object bean, String propertyName, Class clazz)
  9. newInstance(ProceedingJoinPoint thisJoinPoint, Class clazz, Object... newArgs)