Java Class New Instance newInstance(Class clazz)

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

Description

new Instance

License

Apache License

Declaration

public static <T> T newInstance(Class<T> clazz) throws IllegalArgumentException, InstantiationException,
            IllegalAccessException, InvocationTargetException 

Method Source Code

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

import java.lang.reflect.Constructor;

import java.lang.reflect.InvocationTargetException;

public class Main {
    public static <T> T newInstance(Class<T> clazz) throws IllegalArgumentException, InstantiationException,
            IllegalAccessException, InvocationTargetException {
        Constructor<?>[] constructors = clazz.getDeclaredConstructors();
        for (Constructor<?> constructor : constructors) {
            if (!constructor.isAccessible())
                constructor.setAccessible(true);
            Class<?>[] types = constructor.getParameterTypes();
            Object[] params = new Object[types.length];
            for (int i = 0; i < types.length; i++) {
                if (types[i] == byte.class) {
                    params[i] = (byte) 0;
                } else if (types[i] == short.class) {
                    params[i] = (short) 0;
                } else if (types[i] == int.class) {
                    params[i] = 0;//from  w  w  w  .j a  va 2  s .  c o m
                } else if (types[i] == float.class) {
                    params[i] = 0f;
                } else if (types[i] == double.class) {
                    params[i] = 0d;
                } else if (types[i] == long.class) {
                    params[i] = 0L;
                } else if (types[i] == boolean.class) {
                    params[i] = false;
                }
            }
            return (T) constructor.newInstance(params);
        }
        return null;
    }
}

Related

  1. newInstance(Class c)
  2. newInstance(Class c)
  3. newInstance(Class c, Class[] argTypes, Object[] args)
  4. newInstance(Class cl)
  5. newInstance(Class classOf)
  6. newInstance(Class clazz)
  7. newInstance(Class clazz)
  8. newInstance(Class clazz)
  9. newInstance(Class clazz)