Java Class New Instance newInstance(Class type)

Here you can find the source of newInstance(Class type)

Description

new Instance

License

Open Source License

Declaration

public static <T> T newInstance(Class<T> type) 

Method Source Code

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

import java.lang.reflect.*;

public class Main {
    public static <T> T newInstance(Class<T> type) {
        try {//from w  ww . j a v a  2  s.  com
            Constructor<T> constructor = type.getDeclaredConstructor();
            if (type.getEnclosingClass() != null && constructor == null) {
                // inner, no static class
                throw new IllegalArgumentException("Inner class is not supported");
                // Object enclosing = newInstance(type.getEnclosingClass());
                // Constructor<T> constructor = type.getConstructor(enclosing.getClass());
                // return constructor.newInstance(enclosing);

            } else {
                if (!constructor.isAccessible()) {
                    constructor.setAccessible(true);
                }
                return constructor.newInstance();
            }
        } catch (ReflectiveOperationException e) {
            throw new RuntimeException(e);
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> T newInstance(Class<T> type, Constructor<?> constructor, Object... parameters) {
        try {
            return (T) constructor.newInstance(parameters);
        } catch (ReflectiveOperationException e) {
            return null;
        }
    }
}

Related

  1. newInstance(Class theClass, Object... initArgs)
  2. newInstance(Class theClass, String className)
  3. newInstance(Class theCls)
  4. newInstance(Class type)
  5. newInstance(Class type)
  6. newInstance(Class type)
  7. newInstance(Class type)
  8. newInstance(Class type)
  9. newInstance(Class type)