Three methods of class instantiation

The ultimate purpose of class instantiation is nothing more than to use the properties or methods of class objects. The following describes the effects of three instantiation methods:

First declare a StudentEntity entity class

package com.zlt.others;

public class StudentEntity {
    private String userName;
    private int password;

    public String getUserName() {
        return userName;

    public void setUserName(String userName) {
        this.userName = userName;

    public int getPassword() {
        return password;

    public void setPassword(int password) {
        this.password = password;


1. Class instantiation using normal new

//Instantiate StudentEntity object
StudentEntity studentEntity = new StudentEntity();
//Call the object's properties and methods
The results are as follows:

2. Use "class. Class" to get, usually in hibernate

//Specifies the type of instanced object
StudentEntity studentEntity1 = StudentEntity.class.newInstance();
//Call the set method of the instantiated object to write
studentEntity1.setUserName("Utilization class.class To instantiate");
The results are as follows:

Use class. Class to instantiate

3. Use the static method of Class to obtain: public static Class <? > forname (string classname) throws classnotfoundexception;

Class<?> student = Class.forName("com.zlt.others.StudentEntity");
//You do not need to specify the type of return object
Object ob = student.newInstance();
//Read the specified method of the object
Method setNameMethod = student.getMethod("setUserName", String.class);
//Call this method with reflection
Method getUserNameMethod = student.getMethod("getUserName");
//Read the specified properties of the object
Field userName = student.getDeclaredField("userName");
//Unseal: when the attribute is private and the reflection access is used, set setAccessible to true to unseal the private attribute
The results are as follows:


1. First, new and newInstance methods, with new as the keyword and newInstance as the method.

2. Creation method: new creates a new class, and newInstance uses the class loading mechanism. When creating a class with new, the class can not be loaded. When using the newInstance method, make sure that the class is loaded. Class.forName() starts the class loader.

3. Limitations: newInstance: weak type, low efficiency, can only call nonparametric construction, decoupling

new: strong type, relatively efficient, can call any public construct.

Tags: Attribute Hibernate

Posted on Mon, 04 May 2020 15:43:27 -0400 by robsgaming