Java Class New Instance newInstance(Class theClass, String className)

Here you can find the source of newInstance(Class theClass, String className)

Description

Creates a new zero-arg instance of the specified class

License

Open Source License

Declaration

@SuppressWarnings("unchecked")
public static <T> T newInstance(Class<T> theClass, String className) 

Method Source Code


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

import java.lang.reflect.Constructor;
import java.util.Map;
import com.google.common.collect.Maps;

public class Main {
    private static final Class<?>[] EMPTY_ARRAY = new Class[] {};
    private static final Map<String, Constructor<?>> CONSTRUCTOR_CACHE = Maps.newConcurrentMap();

    /**/*from  www .  ja v  a  2s .  c  o m*/
     * Creates a new zero-arg instance of the specified class
     */
    @SuppressWarnings("unchecked")
    public static <T> T newInstance(Class<T> theClass, String className) {
        try {
            Constructor<T> ctr = (Constructor<T>) CONSTRUCTOR_CACHE.get(className);
            if (ctr == null) {

                Class<T> clazz = (Class<T>) Class.forName(className);
                ctr = (Constructor<T>) clazz.getDeclaredConstructor(EMPTY_ARRAY);
                ctr.setAccessible(true);
                CONSTRUCTOR_CACHE.put(className, ctr);
            }
            return ctr.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("Failed to instantiate task: " + className, e);
        }
    }
}

Related

  1. newInstance(Class theClass)
  2. newInstance(Class theClass)
  3. newInstance(Class theClass)
  4. newInstance(Class theClass, Class[] parameterTypes, Object[] initargs)
  5. newInstance(Class theClass, Object... initArgs)
  6. newInstance(Class theCls)
  7. newInstance(Class type)
  8. newInstance(Class type)
  9. newInstance(Class type)