Several ways and details of creating objects in Java

Five ways to create objects in Java

Constructor called using new keyword} →
Constructor called using newInstance method} → of Class class
Constructor called using newInstance method} → of constructor class
Use clone method} → no constructor called
Use deserialization} → no constructor called

1. Use the new keyword

This is the most common and simple way to create objects. In this way, we can call any constructor (parameterless and parameterized).

Student student = new Student();

2. newInstance method of class

Student student2 = (Student)Class.forName(className).newInstance();   
// Or:  
Student stu = Student.class.newInstance();  

JDK 1.8, class source code

public final class Class<T> implements java.io.Serializable,  
                              GenericDeclaration,  
                              Type,  
                              AnnotatedElement {  
    // other code  

    public T newInstance()  
        throws InstantiationException, IllegalAccessException  
    {  
        // ...  

        // Constructor lookup  
        // other code   
        if (cachedConstructor == null) {  
            if (this == Class.class) {  
                throw new IllegalAccessException(  
                    "Can not call newInstance() on the Class for java.lang.Class"  
                );  
            }  
            try {  
                // ...  
                final Constructor<T> c = getConstructor0(empty, Member.DECLARED);  
                // 1. Constructor is public or method visible  
                // ...  
                cachedConstructor = c;  
            } catch (NoSuchMethodException e) {  
                throw (InstantiationException)  
                    new InstantiationException(getName()).initCause(e);  
            }  
        }  
        Constructor<T> tmpConstructor = cachedConstructor;  
        // ...  
        // Run constructor  
        try {  
            return tmpConstructor.newInstance((Object[])null);// 2. non-parameter constructor   
        } catch (InvocationTargetException e) {  
            // ...  
        }  
    }  

    // other code  
}  

Tags: Java JDK

Posted on Mon, 06 Jan 2020 14:11:54 -0800 by dc_jt