Java Class New Instance newInstance(Class cls, Map, Constructor> cache)

Here you can find the source of newInstance(Class cls, Map, Constructor> cache)

Description

new Instance

License

Apache License

Declaration

@SuppressWarnings("unchecked")
    static <T> T newInstance(Class<?> cls, Map<Class<?>, Constructor<?>> cache) 

Method Source Code


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

import java.lang.reflect.Constructor;

import java.util.Map;

public class Main {
    @SuppressWarnings("unchecked")
    static <T> T newInstance(Class<?> cls, Map<Class<?>, Constructor<?>> cache) {
        final Constructor ctor = getDefaultConstructor(cls, cache);
        try {// w w w.  jav a2s. c  o m
            return (T) ctor.newInstance();
        } catch (Throwable t) {
            throw new RuntimeException("Failed to instantiate " + cls.getName(), t);
        }
    }

    static Constructor<?> getDefaultConstructor(Class<?> cls, Map<Class<?>, Constructor<?>> cache) {
        if (cache != null) {
            Constructor ctor = cache.get(cls);
            if (ctor != null)
                return ctor;
        }
        final Constructor[] constructorArray = cls.getDeclaredConstructors();
        Constructor constructor = null;
        for (Constructor ct : constructorArray) {
            if (ct.getParameterTypes() != null && ct.getParameterTypes().length != 0)
                continue;
            constructor = ct;
            if (constructor.getGenericParameterTypes().length == 0)
                break;
        }
        if (constructor == null)
            throw new IllegalStateException("No default constructor found for " + cls.getName());
        constructor.setAccessible(true);
        if (cache != null)
            cache.put(cls, constructor);
        return constructor;
    }
}

Related

  1. newInstance(Class clazz, Object... args)
  2. newInstance(Class clazz, Object... args)
  3. newInstance(Class cls)
  4. newInstance(Class cls)
  5. newInstance(Class cls)
  6. newInstance(Class componentType, int... dimensions)
  7. newInstance(Class entity)
  8. newInstance(Class theClass, Class expected)
  9. newInstance(Class interfaceDefinition, String className, ClassLoader classLoader)