Creates an instance of an object type.

@param type an object type (factory function) to create.
@param args arguments for the object constructor.
@return the created object instance.
@throws Exception when constructors with parameters are not supported
161730
public static Object createInstanceByType(Class<?> type, Object... args) throws Exception {
		if (args.length == 0) {
			Constructor<?> constructor = type.getConstructor();
			return constructor.newInstance();
		} else {
			throw new UnsupportedException(null, "NOT_SUPPORTED", "Constructors with parameters are not supported");
		}
	}
306937
@SuppressWarnings("unchecked")
    public static DataProviderFactory create(final Object... args) {
        // Find the implementation for the DataProviderFactory.
        final Class<? extends DataProviderFactory> dataProviderClass = findDataProviderImpl();

        // Find the constructor that matches the arguments passed.
        final DataProviderFactory factory;
        try {
            Constructor<? extends DataProviderFactory> dataProviderConstructor = null;
            final Constructor[] constructors = dataProviderClass.getDeclaredConstructors();
            for (final Constructor constructor : constructors) {
                final Class<?>[] params = constructor.getParameterTypes();
                boolean matches = false;

                // Ensure that all the argument match
                if (args.length == params.length) {
                    matches = true;
                    for (int i = 0; i < params.length; i++) {
                        if (!params[i].isAssignableFrom(args[i].getClass())) {
                            matches = false;
                        }
                    }
                }

                // If the constructor matches then break the loop, as we've found the matching constructor
                if (matches) {
                    dataProviderConstructor = constructor;
                    break;
                }
            }

            // Make sure a constructor was found
            if (dataProviderConstructor != null) {
                factory = dataProviderConstructor.newInstance(args);
            } else {
                factory = null;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return factory;
    }
849510
public Object execute(Object[] arguments) throws Exception
	{
		try
		{
			if (this.method == null)
			{
				if (this.parameterTypes == null)
					this.parameterTypes = PROXY.toParameterTypes(arguments);

				this.method = PROXY.findMethod(this.targetClass,
						this.methodName, this.parameterTypes);
			}

			return this.method.invoke(target, arguments);
		}
		catch (IllegalArgumentException e)
		{
			throw new IllegalArgumentException(target.getClass().getName()+"."+this.method+"("+Debugger.toString(e)+")");
		}
		catch (NoSuchMethodException e)
		{
			throw e;
		}
		catch (IllegalAccessException e)
		{
			throw e;
		}
		catch (InvocationTargetException e)
		{
			if (e.getCause() instanceof Exception)
				throw (Exception) e.getCause();
			else
				throw e;
		}

	}
942886
public static synchronized <T> T createNiceMockAndExpectNew(Class<T> type, Object... arguments) throws Exception {
        T mock = createNiceMock(type);
        IExpectationSetters<T> expectationSetters = expectNiceNew(type, arguments);
        if (expectationSetters != null) {
            expectationSetters.andReturn(mock);
        }
        return mock;
    }
674327
public static <T> T instantiate(Class<T> type) {
        try {
            return BeanIntrospector.SHARED.findIntrospection(type).map(BeanIntrospection::instantiate).orElseGet(() -> {
                try {
                    Logger log = ClassUtils.REFLECTION_LOGGER;
                    if (log.isDebugEnabled()) {
                        log.debug("Reflectively instantiating type: " + type);
                    }
                    return type.newInstance();
                } catch (Throwable e) {
                    throw new InstantiationException("Could not instantiate type [" + type.getName() + "]: " + e.getMessage(), e);
                }
            });
        } catch (Throwable e) {
            throw new InstantiationException("Could not instantiate type [" + type.getName() + "]: " + e.getMessage(), e);
        }
    }
1332993
public static <T> T newInstance(Type type) {
        try {
            Class<T> clazz = (Class<T>) getClass(type);
            if (clazz == null) {
                return null;
            }
            return clazz.newInstance();
        } catch (Exception e) {
            log.warn("new instance fail :{}", e.getCause().toString());
            throw new NewInstanceException(e.getCause().toString());
        }
    }
1005841
static <T> T newInstance(final Class<?> clazz, final Class<?>[] argumentTypes, final Object[] arguments,
        final Class<T> expectedType) {
        // Precondition checks
        if (clazz == null) {
            throw new IllegalArgumentException("Class must be specified");
        }
        if (argumentTypes == null) {
            throw new IllegalArgumentException("ArgumentTypes must be specified. Use empty array if no arguments");
        }
        if (arguments == null) {
            throw new IllegalArgumentException("Arguments must be specified. Use empty array if no arguments");
        }
        if (expectedType == null) {
            throw new IllegalArgumentException("Expected type must be specified");
        }

        // Get the ctor
        final Constructor<?> constructor;
        try {
            constructor = getConstructor(clazz, argumentTypes);
        } catch (final NoSuchMethodException e) {
            throw new RuntimeException("Could not create new instance of " + clazz + " using ctor argument types "
                + Arrays.asList(argumentTypes), e);
        }

        // Create the instance
        final Object obj;
        try {
            obj = constructor.newInstance(arguments);
        } catch (final Exception e) {
            throw new RuntimeException("Could not create a new instance of " + clazz + " using arguments "
                + Arrays.asList(arguments), e);
        }

        // Cast
        try {
            return expectedType.cast(obj);
        } catch (final ClassCastException cce) {
            // Reconstruct so we get some useful information
            throw new ClassCastException("Incorrect expected type, " + expectedType.getName() + ", defined for "
                + obj.getClass().getName());
        }
    }
494873
@SafeVarargs
    public static <T extends ParseTreeListener> T create(Class<T> type, T... delegates) {
        ImmutableList<T> listeners = ImmutableList.copyOf(delegates);
        return Reflection.newProxy(type, new AbstractInvocationHandler() {

            @Override
            @ParametersAreNonnullByDefault
            protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {
                for (T listener : listeners) {
                    method.invoke(listener, args);
                }
                return null;
            }

            @Override
            public String toString() {
                return MoreObjects.toStringHelper("CompositeParseTreeListener")
                        .add("listeners", listeners)
                        .toString();
            }
        });

    }
382426
@SuppressWarnings("rawtypes")
	public static Object instantiate(Class<?> type) throws Exception {
		if (type.isAssignableFrom(ArrayList.class))
			return new ArrayList();
		if (type.isAssignableFrom(LinkedList.class))
			return new LinkedList();
		if (type.isAssignableFrom(HashSet.class))
			return new HashSet();
		if (type.isAssignableFrom(HashMap.class))
			return new HashMap();
		return type.newInstance();
	}
756192
public static Object instantiate(String type, ClassLoader classLoader) {
        try {
            return ClassUtils.forName(type, classLoader)
                .flatMap(InstantiationUtils::tryInstantiate)
                .orElseThrow(() -> new InstantiationException("No class found for name: " + type));
        } catch (Throwable e) {
            throw new InstantiationException("Could not instantiate type [" + type + "]: " + e.getMessage(), e);
        }
    }
515675
public static <T> T invoke( Constructor<T> constructor, Object... args ) throws Throwable
    {
        try
        {
            return constructor.newInstance( args );
        }
        catch (InstantiationException e)
        {
            throw e.getCause();
        }
    }
1371288
public static void main(final String[] args) throws Exception {
    final Injector injector = Tang.Factory.getTang().newInjector(parseCommandLine(args));
    final REEFExecutor reefExecutor = injector.getInstance(REEFExecutor.class);
    reefExecutor.onStart();
  }
1242266
private static void createFactoryInstance() throws Exception {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "createFactoryInstance");
    try {
      Class cls = Class.forName(CONTROL_MESSAGE_FACTORY_CLASS);
      instance = (ControlMessageFactory) cls.newInstance();
    }
    catch (Exception e) {
      FFDCFilter.processException(e, "com.ibm.ws.sib.mfp.ControlMessageFactory.createFactoryInstance", "112");
      SibTr.error(tc,"UNABLE_TO_CREATE_CONTROLFACTORY_CWSIF0041",e);
      throw e;
    }
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "createFactoryInstance");
  }
646613
public T newInstance(Object... args) throws Throwable
    {
        Constructor<? extends T> constructor = ClassUtils.findBestTypedConstructor(klass, args);
        return ClassUtils.invoke(constructor, args);
    }
1321248
@SuppressWarnings({ "unchecked", "TryWithIdenticalCatches" })
  public static <T> T init(
      @NonNull Class<T> type, @NonNull Class[] argClasses, @NonNull Object[] args) {
    try {
      Constructor<T> constructor = type.getDeclaredConstructor(argClasses);
      constructor.setAccessible(true);
      return constructor.newInstance(args);
    } catch (NoSuchMethodException e) {
      throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
      throw new RuntimeException(e);
    } catch (InstantiationException e) {
      throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
      throw new RuntimeException(e);
    }
  }
515051
@SuppressWarnings("unchecked")
	private T createInstance(final String className, final Object... arguments) {
		try {
			Class<?> implementation = Class.forName(className, false, classLoader);
			if (service.isAssignableFrom(implementation)) {
				return (T) implementation.getDeclaredConstructor(argumentTypes).newInstance(arguments);
			} else {
				InternalLogger.log(Level.ERROR, "Class '" + className + "' does not implement servcie interface '" + service + "'");
			}
		} catch (ClassNotFoundException ex) {
			InternalLogger.log(Level.ERROR, "Service implementation '" + className + "' not found");
		} catch (NoSuchMethodException ex) {
			InternalLogger.log(Level.ERROR, "Service implementation '" + className + "' has no matching constructor");
		} catch (InstantiationException ex) {
			InternalLogger.log(Level.ERROR, "Service implementation '" + className + "' is not instantiable");
		} catch (IllegalAccessException ex) {
			InternalLogger.log(Level.ERROR, "Constructor of service implementation '" + className + "' is not accessible");
		} catch (IllegalArgumentException ex) {
			InternalLogger.log(Level.ERROR, "Illegal arguments for constructor of service implementation '" + className + "'");
		} catch (InvocationTargetException ex) {
			InternalLogger.log(Level.ERROR, ex.getTargetException(), "Failed creating service implementation '" + className + "'");
		}

		return null;
	}
337136
public static Object newInstance(Class type) {
        Constructor _constructor = null;
        Object[] _constructorArgs = new Object[0];
        try {
            _constructor = type.getConstructor(new Class[] {});// 先尝试默认的空构造函数
        } catch (NoSuchMethodException e) {
            // ignore
        }

        if (_constructor == null) {// 没有默认的构造函数，尝试别的带参数的函数
            Constructor[] constructors = type.getConstructors();
            if (constructors.length == 0) {
                throw new UnsupportedOperationException("Class[" + type.getName() + "] has no public constructors");
            }
            _constructor = constructors[0];// 默认取第一个参数
            Class[] params = _constructor.getParameterTypes();
            _constructorArgs = new Object[params.length];
            for (int i = 0; i < params.length; i++) {
                _constructorArgs[i] = getDefaultValue(params[i]);
            }
        }

        return ReflectUtils.newInstance(_constructor, _constructorArgs);
    }