java 产生对象_【JAVA产生对象的几种方式】

本文探讨了Java对象的四种创建方式:new、反射、clone和序列化,重点介绍了序列化在持久化和网络传输中的应用,包括序列化与反序列化的原理和实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

/**

* java生成对象的几种方式

*   1、new

*   2、反射

*      Class.forName

*      类.class

*      对象.getClass()

*   3、clone

*      必须实现Cloneable接口,实现protected Object clone()方法

*   4、序列化

1.概念

序列化:把Java对象转换为字节序列的过程。

反序列化:把字节序列恢复为Java对象的过程。

2.用途

对象的序列化主要有两种用途:

1) 把对象的字节序列永久地保存到硬盘上,通常存放在一个文件中;

2) 在网络上传送对象的字节序列。

* @author Administrator

*/

public class Demo1 {

/**

* @param args

* @throws Exception

*/

public static void main(String[] args) throws Exception {

//一、使用new

Student s = new Student();

s.print();

//二、使用反射

Class c = Class.forName("Student");

Student c1=(Student)c.newInstance();

c1.print();

System.out.println("1、通过类本身获得对象");

Class clazz = Student.class;

Student s11=(Student)clazz.newInstance();

s11.print();

Student student1 = new Student();

clazz = student1.getClass();

Student s12=(Student)clazz.newInstance();

s12.print();

//三、使用clone

/**

* implements Cloneable

* protected Object clone()

*/

Student s1 = (Student) s.clone();

s1.print();

//  Exception in thread "main" java.lang.CloneNotSupportedException:

//四、使用Serializable

System.out.println(" 序列化对象 ");

//序列化对象

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("C:\\objectFile.obj"));

Student student = new Student();

out.writeObject(student);    //写入student对象

out.close();

System.out.println(" 反序列化对象 ");

//反序列化对象

ObjectInputStream in = new ObjectInputStream(new FileInputStream("C:\\objectFile.obj"));

Student obj3 = (Student) in.readObject();

obj3.print();

in.close();

}

}

-----------------------------------

import java.io.Serializable;

public class Student implements Serializable{

private String id;

private String name;

private int age;

public Student(){

System.out.println(" Student Constructor");

}

public void print() {

System.out.println(" Student print method called!!!!");

}

@Override

protected Object clone() throws CloneNotSupportedException {

// TODO Auto-generated method stub

return super.clone();

}

public Student(String id, String name, int age) {

super();

this.id = id;

this.name = name;

this.age = age;

System.out.println(" Student(id,name,age) Constructor");

}

public String getId() {

return id;

}

public void setId(String id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getAge() {

return age;

}

public void setAge(int age) {  this.age = age; }     }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值