Java Class New Instance newInstanceWithoutInit(Class clazz)

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

Description

new Instance Without Init

License

Open Source License

Declaration

public static <T> T newInstanceWithoutInit(Class<T> clazz) 

Method Source Code


//package com.java2s;
import sun.reflect.ReflectionFactory;
import java.lang.reflect.Constructor;

public class Main {
    public static <T> T newInstanceWithoutInit(Class<T> clazz) {
        try {/*  w w  w.j  a va  2  s  .  c  om*/
            ReflectionFactory rf = ReflectionFactory.getReflectionFactory();
            Constructor objDef = Object.class.getDeclaredConstructor();
            Constructor intConstr = rf.newConstructorForSerialization(clazz, objDef);

            return clazz.cast(intConstr.newInstance());
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new IllegalStateException("Cannot create object", e);
        }
    }

    public static <T> T newInstance(Class<T> classOf) {
        try {
            return classOf.newInstance();
        } catch (InstantiationException | IllegalAccessException ex) {
            return null;
        }
    }
}

Related

  1. newInstanceOrThrow(final Class clazz)
  2. newInstancesViaMetaAnnotation(Class declarator, Class metaAnnotationClass, Class expected)
  3. newInstanceViaAnnotation(Class declarator, Annotation annotation, Class expected, Annotation parameter)
  4. newInstanceWithDefaults(Class annotationType)
  5. newInstanceWithFill(Class componentType, int length, Object filledValue)
  6. newInstanceWithParameterTypes(Constructor constructor)