Java 中创建对象的5种方式

时间:2022-08-30 17:33:45

java有5种创建对象的方式,下面我用这个Employee类创建对象:

 package com.example.string.Object;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;

public class ObjectCreation {

/**
* @param args
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public static void main(String[] args) throws Exception {
Employee emp1 = new Employee();
emp1.setName("Naresh");
System.out.println(emp1 + ", hashcode :" + emp1.hashCode());


Employee emp2 = (Employee) Class.forName("com.example.string.Object.Employee").newInstance();
emp2.setName("Rishi");
System.out.println(emp2 + ", hashcode :" + emp2.hashCode());

Constructor<Employee> constructor = Employee.class.getConstructor();
Employee emp3 = constructor.newInstance();
emp3.setName("Yogesh");
System.out.println(emp3 + ", hashcode :" + emp3.hashCode());

Employee emp4 = (Employee) emp3.clone();
emp4.setName("Atul");
System.out.println(emp4 + ", hashcode :" + emp4.hashCode());

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("data.obj"));
oos.writeObject(emp4);
oos.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data.obj"));
Employee emp5 = (Employee) ois.readObject();
ois.close();
emp5.setName("Akash");
System.out.println(emp5 + ", hashcode :" + emp5.hashCode());

}
}

2: 创建Employee类:

package com.example.string.Object;

import java.io.Serializable;

public class Employee implements Serializable, Cloneable{


private static final long serialVersionUID = 1L;
private String name;
public Employee(){
System.out.println("Employee Constructor Called...");
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}

@Override
public String toString() {
return "Employee [name=" + name + "]";
}

@Override
protected Object clone() {
Object obj = null;
try {
obj = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return obj;
}
}

程序会输出:

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