Use the simplest description to differentiate between the new keyword and the Newinstance () method:
Newinstance: Weak type. Low efficiency. Only parameterless constructs can be called.
NEW: Strongly typed. relatively efficient. Can invoke any public construct.
Newinstance () is a method, and new is a keyword, and second, the use of newinstance () under class is limited, because it generates objects that can only invoke parameterless constructors, and the use of the new keyword to generate objects does not have this limitation.
Class.forName ("") returns the class
Class.forName (""). Newinstance () returns an object
As Java developers, we create a lot of objects every day, but we often use dependency management systems like spring to create objects. However, there are many ways to create objects, which we will learn from this article.
There are 5 ways to create objects in Java, with examples of them and their bytecode:
Use the New keyword |
}→ called the constructor |
Using the class Newinstance method |
}→ called the constructor |
Using the Newinstance method of the constructor class |
}→ called the constructor |
Using the Clone method |
}→ no constructor is called |
Using deserialization |
}→ no constructor is called |
If you run the program at the end, you will find that method 4,5 creates the object with the constructor, and the method does not call the constructor.
1. Use the New keyword
This is the most common and simplest way to create objects. In this way, we can call any constructor (with no arguments and with parameters).
< Span style= "color: #ff0000;" >employee emp1 = new employee (); </span> |
0 : new # 19 // class org/programming/mitra/exercises/Employee 3 : dup 4 : invokespecial # 21 // Method org/programming/mitra/exercises/Employee."":()V |
2. Using the class Newinstance method
We can also use the class class's Newinstance method to create an object. This newinstance method calls the parameterless constructor to create the object.
We can create an object by calling the Newinstance method in the following way:
Employee emp2 = (Employee) Class.forName(
"org.programming.mitra.exercises.Employee"
).newInstance();
Or:
Employee emp2 = Employee.
class
.newInstance();
3. Using the Newinstance method of the constructor class
Like the Newinstance method of class, there is also a newinstance method in the Java.lang.reflect.Constructor class that can create objects. We can call the parameterized and private constructors through this newinstance method.
Constructor<Employee> constructor = Employee.
class
.getConstructor();
Employee emp3 = constructor.newInstance();
These two newinstance methods are what we call reflection. In fact, class's Newinstance method internally calls constructor's Newinstance method. This is also why many frameworks, such as spring, Hibernate, struts, etc. use the latter.
4. Using the Clone method
Whenever we invoke the Clone method of an object, the JVM creates a new object that copies the contents of the preceding object in its entirety. Creating an object with the Clone method does not call any constructors.
To use the Clone method, we need to implement the Cloneable interface first and implement its definition of the Clone method.
Employee emp4 = (Employee) emp3.clone();
5. Using deserialization
When we serialize and deserialize an object, the JVM creates a separate object for us. When deserializing, the JVM creates an object and does not call any constructors.
In order to deserialize an object, we need to have our class implement the Serializable interface
ObjectInputStream in =
new
ObjectInputStream(
new
FileInputStream(
"data.obj"
));
Employee emp5 = (Employee) in.readObject();
我们从上面的字节码片段可以看到,除了第
1
个方法,其他
4
个方法全都转变为invokevirtual(创建对象的直接方法),第一个方法转变为两个调用,
new
和invokespecial(构造函数调用)。
Example
Let's take a look at creating an object for the following employee class:
1 classEmployeeImplementscloneable, Serializable {2 Private Static Final LongSerialversionuid = 1L;3 PrivateString name;4 PublicEmployee () {5System.out.println ("Employee Constructor called ...");6 }7 PublicString GetName () {8 returnname;9 }Ten Public voidsetName (String name) { One This. Name =name; A } - @Override - Public inthashcode () { the Final intPrime = 31; - intresult = 1; -result = Prime * result + ((name = =NULL) ? 0: Name.hashcode ()); - returnresult; + } - @Override + Public Booleanequals (Object obj) { A if( This==obj) at return true; - if(obj = =NULL) - return false; - if(GetClass ()! =Obj.getclass ()) - return false; -Employee other =(Employee) obj; in if(Name = =NULL) { - if(Other.name! =NULL) to return false; +}Else if(!name.equals (other.name)) - return false; the return true; * } $ @OverridePanax Notoginseng PublicString toString () { - return"Employee [name=" + name + "]"; the } + @Override A PublicObject Clone () { theObject obj =NULL; + Try { -obj =Super. Clone (); $}Catch(clonenotsupportedexception e) { $ e.printstacktrace (); - } - returnobj; the } -}
In the following Java program, we will create the employee object in 5 ways.
1 Public classobjectcreation {2 Public Static voidMain (String ... args)throwsException {3 //by using new keyword4Employee EMP1 =NewEmployee ();5Emp1.setname ("Naresh");6System.out.println (Emp1 + ", Hashcode:" +Emp1.hashcode ());7 //by using Class class ' s Newinstance () method8Employee EMP2 = (employee) class.forname ("Org.programming.mitra.exercises.Employee")9 . newinstance ();Ten //Or We can simply do this One //Employee emp2 = Employee.class.newInstance (); AEmp2.setname ("Rishi"); -System.out.println (EMP2 + ", Hashcode:" +Emp2.hashcode ()); - //by using Constructor class ' s newinstance () method theConstructor<employee> Constructor = Employee.class. GetConstructor (); -Employee Emp3 =constructor.newinstance (); -Emp3.setname ("Yogesh"); -System.out.println (Emp3 + ", Hashcode:" +Emp3.hashcode ()); + //by using Clone () method -Employee Emp4 =(Employee) Emp3.clone (); +Emp4.setname ("Atul"); ASystem.out.println (Emp4 + ", Hashcode:" +Emp4.hashcode ()); at //by using deserialization - //Serialization -ObjectOutputStream out =NewObjectOutputStream (NewFileOutputStream ("Data.obj")); - Out.writeobject (emp4); - out.close (); - //deserialization inObjectInputStream in =NewObjectInputStream (NewFileInputStream ("Data.obj")); -Employee EMP5 =(Employee) in.readobject (); to in.close (); +Emp5.setname ("Akash"); -System.out.println (Emp5 + ", Hashcode:" +Emp5.hashcode ()); the } *}
The program will output:
Employee Constructor Called...
Employee [name=Naresh], hashcode : -
1968815046
Employee Constructor Called...
Employee [name=Rishi], hashcode :
78970652
Employee Constructor Called...
Employee [name=Yogesh], hashcode : -
1641292792
Employee [name=Atul], hashcode :
2051657
Employee [name=Akash], hashcode :
63313419
Five ways to create objects in Java