Java Class New Instance newInstance(Class type, Object... args)

Here you can find the source of newInstance(Class type, Object... args)

Description

new Instance

License

Open Source License

Declaration

public static <T> T newInstance(Class<T> type, Object... args) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Main {
    public static <T> T newInstance(Class<T> type, Object... args) {
        Class<?>[] classArgs = new Class<?>[args.length];
        for (int i = 0; i < classArgs.length; i++)
            classArgs[i] = args[i].getClass();
        return newInstance(type, classArgs, args);
    }/* ww  w .  j av a  2s. co  m*/

    public static <T> T newInstance(Class<T> type, Class<?>[] classArgs, Object... args) {
        Constructor<T> constructor = null;
        try {
            constructor = type.getConstructor(classArgs);
        } catch (SecurityException e) {
            e.printStackTrace();
            return null;
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            return null;
        }
        try {
            return constructor.newInstance(args);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Related

  1. newInstance(Class type)
  2. newInstance(Class type)
  3. newInstance(Class type)
  4. newInstance(Class type, Class declarator, Annotation annotation)
  5. newInstance(Class type, Class[] parameterTypes, Object[] args)
  6. newInstance(Class type, Object... params)
  7. newInstance(Constructor c, List parameters)
  8. newInstance(Constructor constructor, Object... args)
  9. newInstance(Constructor constructor, Object... arguments)

  10. HOME | Copyright © www.java2s.com 2016