Here you can find the source of newInstance(final String className, final Object[] args)
Parameter | Description |
---|---|
className | Name of class to be created. |
args | Constructor arguments. |
public static Object newInstance(final String className, final Object[] args)
//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); } } }