準備工作:首先創(chuàng)建一個學生類。
import java.io.Serializable;
public class Student implements Serializable {
String name;
int age;
int score;
public Student() {
}
public Student(String name, int age, int score) {
this.name = name;
this.age = age;
this.score = score;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
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;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
1.通過new關鍵字來創(chuàng)建對象。
Student s1=new Student("張三",15,78);
2.通過反射的構造方法來創(chuàng)建對象。
//反射
Constructor<Student> declaredConstructor = Student.class.getDeclaredConstructor(String.class, int.class, int.class);
Student stu = declaredConstructor.newInstance("熊愛明", 15, 89);
System.out.println(stu);
?不懂反射的同學可以看這里:你還不會反射吧,快來吧?。?!_明天更新的博客-CSDN博客
?3.通過克隆來創(chuàng)建對象。
import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;
import sun.misc.Unsafe;
import java.io.*;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Constructor;
public class Test {
public static void main(String[] args) throws Throwable {
//克隆
Student student=new Student("張三",15,78);
Object clone = student.clone();
System.out.println(clone);
}
}
4.通過反序列化來創(chuàng)建對象。(Student類實現(xiàn)Serializable接口)文章來源:http://www.zghlxwxcb.cn/news/detail-680312.html
import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;
import sun.misc.Unsafe;
import java.io.*;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Constructor;
public class Test {
public static void main(String[] args) throws Throwable {
//反序列化
byte[] bytes = serialize(student);
Student s2 = (Student)deserialize(bytes);
System.out.println(s2);
}
private static byte[] serialize(Student student) throws IOException{
ByteArrayOutputStream baos=new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(student);
byte[] bytes = baos.toByteArray();
return bytes;
}
private static Object deserialize(byte[] bytes) throws IOException,ClassNotFoundException{
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
return ois.readObject();
}
}
5.通過MethodHandle? API來創(chuàng)建對象。文章來源地址http://www.zghlxwxcb.cn/news/detail-680312.html
//MethodHandle API
MethodHandle constructor = MethodHandles.lookup().findConstructor(Student.class, MethodType.methodType(void.class, String.class, int.class, int.class));
Student s = (Student)constructor.invoke("李四", 45, 89);
System.out.println(s);
到了這里,關于Java創(chuàng)建對象的方式你知道幾種???的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!