Java Class New Instance newInstance(Class cls)

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

Description

new Instance

License

Apache License

Declaration

private static Object newInstance(Class<?> cls) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.lang.reflect.*;

public class Main {
    private static Object newInstance(Class<?> cls) {
        try {/*from w  w  w  .  j  a va  2  s  .  c  om*/
            return cls.newInstance();
        } catch (Throwable t) {
            try {
                Constructor<?>[] constructors = cls.getConstructors();
                if (constructors != null && constructors.length == 0) {
                    throw new RuntimeException("Illegal constructor: " + cls.getName());
                }
                Constructor<?> constructor = constructors[0];
                if (constructor.getParameterTypes().length > 0) {
                    for (Constructor<?> c : constructors) {
                        if (c.getParameterTypes().length < constructor.getParameterTypes().length) {
                            constructor = c;
                            if (constructor.getParameterTypes().length == 0) {
                                break;
                            }
                        }
                    }
                }
                return constructor.newInstance(new Object[constructor.getParameterTypes().length]);
            } catch (InstantiationException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    }
}

Related

  1. newInstance(Class clazz)
  2. newInstance(Class clazz)
  3. newInstance(Class clazz, Class[] args, Object[] objects)
  4. newInstance(Class clazz, Object... args)
  5. newInstance(Class clazz, Object... args)
  6. newInstance(Class cls)
  7. newInstance(Class cls)
  8. newInstance(Class cls, Map, Constructor> cache)
  9. newInstance(Class componentType, int... dimensions)