Java Class New Instance newInstance(Class type)

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

Description

new Instance

License

Apache License

Declaration

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

Method Source Code

//package com.java2s;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;

public class Main {
    private static Map<Class<?>, Constructor<?>> constructorCache = new HashMap<Class<?>, Constructor<?>>();

    public static <T> T newInstance(Class<T> type) {
        try {/*from w ww .  j  a v a 2 s.  com*/
            Constructor<T> customConstructor = getMungedConstructor(type);
            return customConstructor.newInstance(new Object[0]);
        } catch (Exception e) {
            throw new RuntimeException(
                    "Cannot construct " + type.getName(), e);
        }
    }

    @SuppressWarnings({ "unchecked" })
    public static <T> Constructor<T> getMungedConstructor(Class<T> type) {
        try {
            synchronized (constructorCache) {
                Constructor<?> c = constructorCache.get(type);
                if (c != null) {
                    return (Constructor<T>) c;
                }
                sun.reflect.ReflectionFactory factory = sun.reflect.ReflectionFactory
                        .getReflectionFactory();
                c = factory.newConstructorForSerialization(type,
                        Object.class.getDeclaredConstructor(new Class[0]));
                constructorCache.put(type, c);
                return (Constructor<T>) c;
            }
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }
}

Related

  1. newInstance(Class theCls)
  2. newInstance(Class type)
  3. newInstance(Class type)
  4. newInstance(Class type)
  5. newInstance(Class type)
  6. newInstance(Class type)
  7. newInstance(Class type)
  8. newInstance(Class type)
  9. newInstance(Class type)