Java Class New Instance newInstance(Class klass)

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

Description

new Instance

License

Apache License

Declaration

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

Method Source Code


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

import java.lang.reflect.Constructor;

import java.util.Arrays;

public class Main {

    public static <T> T newInstance(Class<T> klass) {
        try {/*from  www  .  ja  va 2 s .c  om*/
            return (T) klass.newInstance();
        } catch (Exception e) {
            throw new IllegalArgumentException("instance class[" + klass.getName() + "] with ex:", e);
        }
    }

    /**
     * 
     * @param klass
     * @param cstTypes
     * @param cstParameters
     * @return
     */
    public static <T> T newInstance(Class<T> klass, Class<?>[] cstTypes, Object... cstParameters) {
        try {
            Constructor<T> cst = klass.getConstructor(cstTypes);
            return cst.newInstance(cstParameters);
        } catch (Exception e) {
            throw new IllegalArgumentException("instance class[" + klass.getName() + "], cstTypes="
                    + Arrays.toString(cstTypes) + ", " + Arrays.toString(cstParameters) + " with ex:", e);
        }
    }

    /**
     * 
     * @param className
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T newInstance(String className) {
        try {
            return (T) newInstance(classForName(className));
        } catch (Exception e) {
            throw new IllegalArgumentException("instance class[" + className + "] with ex:", e);
        }
    }

    public static Class<?> classForName(String className) {
        try {
            return Class.forName(className, false, Thread.currentThread().getContextClassLoader());

        } catch (Exception ignore) {
            try {
                return Class.forName(className);
            } catch (Exception e) {
                throw new IllegalArgumentException("classForName(" + className + ")  with ex:", e);
            }
        }
    }
}

Related

  1. newInstance(Class componentType, int size)
  2. newInstance(Class elementType, int len)
  3. newInstance(Class klass)
  4. newInstance(Class klass)
  5. newInstance(Class klass)
  6. newInstance(Class klass, Class[] paramTypes, Object... params)
  7. newInstance(Class klass, Object... args)
  8. newInstance(Class listener)
  9. newInstance(Class sourceClass)