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

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

Description

new Instance

License

Open Source License

Declaration

@SuppressWarnings("unchecked")
    public static <T> T newInstance(Class<?> clazz, Object... args) 

Method Source Code


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

import java.lang.reflect.Constructor;

public class Main {
    @SuppressWarnings("unchecked")
    public static <T> T newInstance(Class<?> clazz, Object... args) {
        try {/*  w w  w. ja  v  a 2  s .  co m*/
            if (args == null || args.length == 0) {
                return (T) clazz.newInstance();
            }
            Class<?>[] params = new Class<?>[args.length];
            for (int i = 0; i < args.length; i++) {
                Object arg = args[i];
                params[i] = arg == null ? null : arg.getClass();
            }
            Constructor<?> ctor = clazz.getConstructor(params);
            return (T) ctor.newInstance(args);
        } catch (Throwable e) {
            throw new RuntimeException("Unable to create instance of [" + clazz.getName() + "]", e);
        }

    }
}

Related

  1. newInstance(Class clazz)
  2. newInstance(Class clazz)
  3. newInstance(Class clazz)
  4. newInstance(Class clazz)
  5. newInstance(Class clazz, Class[] args, Object[] objects)
  6. newInstance(Class clazz, Object... args)
  7. newInstance(Class cls)
  8. newInstance(Class cls)
  9. newInstance(Class cls)