【JAVA产生对象的几种方式】
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;
}
}
上一篇: 前向传播(张量)- 实战
下一篇: 八大基本数据类型