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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值