Java Class New Instance newInstance(Class clazz)

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

Description

new Instance

License

Open Source License

Declaration

public static <T> T newInstance(Class<T> clazz) throws Exception 

Method Source Code

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

import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;

import java.util.HashSet;
import java.util.Set;

public class Main {
    private static Set<Class> primitiveSet = new HashSet<Class>();

    public static <T> T newInstance(Class<T> clazz) throws Exception {
        if (primitiveSet.contains(clazz)) {
            return null;
        }//from   w w w  .ja v a2 s . c  o  m
        if (clazz.isMemberClass() && !Modifier.isStatic(clazz.getModifiers())) {
            Constructor constructorList[] = clazz.getDeclaredConstructors();
            Constructor defaultConstructor = null;
            for (Constructor con : constructorList) {
                if (con.getParameterTypes().length == 1) {
                    defaultConstructor = con;
                    break;
                }
            }
            if (defaultConstructor != null) {
                if (defaultConstructor.isAccessible()) {
                    return (T) defaultConstructor.newInstance(new Object[] { null });
                } else {
                    try {
                        defaultConstructor.setAccessible(true);
                        return (T) defaultConstructor.newInstance(new Object[] { null });
                    } finally {
                        defaultConstructor.setAccessible(false);
                    }
                }
            } else {
                throw new Exception("The " + clazz.getCanonicalName() + " has no default constructor!");
            }
        }
        try {
            return clazz.newInstance();
        } catch (Exception e) {
            Constructor<T> constructor = clazz.getDeclaredConstructor();
            if (constructor.isAccessible()) {
                throw new Exception("The " + clazz.getCanonicalName() + " has no default constructor!", e);
            } else {
                try {
                    constructor.setAccessible(true);
                    return constructor.newInstance();
                } finally {
                    constructor.setAccessible(false);
                }
            }
        }
    }
}

Related

  1. newInstance(Class c, Class[] argTypes, Object[] args)
  2. newInstance(Class cl)
  3. newInstance(Class classOf)
  4. newInstance(Class clazz)
  5. newInstance(Class clazz)
  6. newInstance(Class clazz)
  7. newInstance(Class clazz)
  8. newInstance(Class clazz)
  9. newInstance(Class clazz)