java在创建对象时必须_Java中5种创建对象的方式
以下是一些在Java中創建對象的方法:
1、 使用new關鍵字
使用new關鍵字是創建對象的最基本方法。這是在java中創建對象的最常見方法。幾乎99%的對象都是這樣創建的。通過使用這個方法,我們可以調用我們想要調用的任何構造函數(無參數或參數化構造函數)。
//Java program to illustrate creation of Object//using new keyword
public classNewKeywordExample
{
String name= "GeeksForGeeks";public static voidmain(String[] args)
{//Here we are creating Object of//NewKeywordExample using new keyword
NewKeywordExample obj = newNewKeywordExample();
System.out.println(obj.name);
}
}
輸出:
GeeksForGeeks
2、使用New Instance
如果我們知道類的名稱并且如果它有一個公共的默認構造函數,我們就可以通過Class.forName來創建類的對象。forName實際上在Java中加載類,但不創建任何對象。要創建類的對象,必須使用類的newInstance()方法。
//Java program to illustrate creation of Object//using new Instance
public classNewInstanceExample
{
String name= "GeeksForGeeks";public static voidmain(String[] args)
{try{
Class cls= Class.forName("NewInstanceExample");
NewInstanceExample obj=(NewInstanceExample) cls.newInstance();
System.out.println(obj.name);
}catch(ClassNotFoundException e)
{
e.printStackTrace();
}catch(InstantiationException e)
{
e.printStackTrace();
}catch(IllegalAccessException e)
{
e.printStackTrace();
}
}
}
輸出:
GeeksForGeeks
3、使用clone()方法
每當對任何對象調用clone()方法時,JVM實際上會創建一個新對象,并將前一個對象的所有內容復制到該對象中。使用clone方法創建對象不會調用任何構造函數。
要使用clone()方法,類要實現Cloneable接口并且實現clone()方法。
//Java program to illustrate creation of Object//using clone() method
public class CloneExample implementsCloneable
{
@Overrideprotected Object clone() throwsCloneNotSupportedException
{return super.clone();
}
String name= "GeeksForGeeks";public static voidmain(String[] args)
{
CloneExample obj1= newCloneExample();try{
CloneExample obj2=(CloneExample) obj1.clone();
System.out.println(obj2.name);
}catch(CloneNotSupportedException e)
{
e.printStackTrace();
}
}
}
輸出:
GeeksForGeeks
注:
這里我們創建的是現有對象的克隆,而不是任何新對象。
類需要實現可克隆接口,否則將拋出CloneNotSupportedException.
4、使用反序列化
每當我們序列化并反序列化一個對象時,JVM會創建一個單獨的對象。在反序列化,JVM不使用任何構造函數來創建對象。
要反序列化對象,我們需要在類中實現可序列化接口。
序列化對象:
importjava.io.Serializable;importjava.time.LocalDate;/***@author:crelle
* @className:Person
*@version:1.0.0
* @date:2020/8/15
* @description:XX
**/
public class Person implementsSerializable {private static final Long serialVersionUID = 237898764368L;public enumSex {
MALE, FEMALE
}privateString name;privateLocalDate birthday;privateSex gender;privateString emailAddress;private intage;publicPerson() {}publicPerson(String name) {this.name =name;
}public voidprintPerson() {
System.out.println(toString());
}publicString getName() {returnname;
}public voidsetName(String name) {this.name =name;
}publicLocalDate getBirthday() {returnbirthday;
}public voidsetBirthday(LocalDate birthday) {this.birthday =birthday;
}publicSex getGender() {returngender;
}public voidsetGender(Sex gender) {this.gender =gender;
}publicString getEmailAddress() {returnemailAddress;
}public voidsetEmailAddress(String emailAddress) {this.emailAddress =emailAddress;
}public intgetAge() {returnage;
}public void setAge(intage) {this.age =age;
}
@OverridepublicString toString() {return "Person{" +
"name='" + name + '\'' +
", birthday=" + birthday +
", gender=" + gender +
", emailAddress='" + emailAddress + '\'' +
", age=" + age +
'}';
}
}
/**
* @author:crelle
* @className:DeserializationExample
* @version:1.0.0
* @date:2020/9/18
* @description:XX
**/
// Java program to illustrate Serializing
// an Object.
import crelle.test.java.auxiliary.beans.Person;
import java.io.*;
class SerializationExample
{
public static void main(String[] args)
{
try
{
Person d = new Person("crelle");
FileOutputStream f = new FileOutputStream("person.txt");
ObjectOutputStream oos = new ObjectOutputStream(f);
oos.writeObject(d);
oos.close();
f.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
反序列化對象:
/***@author:crelle
* @className:DeserializationExample
*@version:1.0.0
* @date:2020/9/18
* @description:XX
**/
//Java program to illustrate creation of Object//using Deserialization.
importcrelle.test.java.auxiliary.beans.Person;import java.io.*;public classDeserializationExample
{public static voidmain(String[] args)
{try{
Person person;
FileInputStream f= new FileInputStream("person.txt");
ObjectInputStream oos= newObjectInputStream(f);
person=(Person) oos.readObject();
System.out.println(person.getName());
}catch(Exception e)
{
e.printStackTrace();
}
}
}
輸出:
crelle
5、使用Constructor類的newInstance()方法:
這類似于類的newInstance()方法。java.lang.reflect.Constructor類中有一個newInstance()方法,可用于創建對象。通過使用此newInstance()方法,它也可以調用參數化構造函數和私有構造函數。
//Java program to illustrate creation of Object//using newInstance() method of Constructor class
import java.lang.reflect.*;public classReflectionExample
{privateString name;
ReflectionExample()
{
}public voidsetName(String name)
{this.name =name;
}public static voidmain(String[] args)
{try{
Constructorconstructor= ReflectionExample.class.getDeclaredConstructor();
ReflectionExample r=constructor.newInstance();
r.setName("GeeksForGeeks");
System.out.println(r.name);
}catch(Exception e)
{
e.printStackTrace();
}
}
}
輸出:
GeeksForGeeks
總結
以上是生活随笔為你收集整理的java在创建对象时必须_Java中5种创建对象的方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: threejs获取模型坐标_Threej
- 下一篇: java 纯面向对象_Java到底是不是