关于java:java创建对象的五中方式

一:创立一个测试实体

public class Hello implements Cloneable, Serializable {
    public Hello() {
    }
    public void hello() {
        System.out.println("hello world");
 }
} 

二:创建对象

// 形式一:通过new创立

Hello hello1 = new Hello();
hello1.hello();

//形式二:通过class类的newInstance 形式创立
try {
    Class<?> aClass = Class.forName("com.albb.test.entity.Hello");
 Hello hello2 = (Hello) aClass.newInstance();
 hello2.hello();
} catch (Exception e) {
    e.printStackTrace();
}

// 形式三:通过constructor newInstance形式创立
try {
    Class<?> aClass1 = Class.forName("com.albb.test.entity.Hello");
 Constructor<?> constructor = aClass1.getConstructor();
 Hello hello3 = (Hello) constructor.newInstance();
 hello3.hello();
} catch (Exception e) {
    e.printStackTrace();
}

// 形式四:通过clone创立
try {
    Hello h1 = new Hello();
 Hello h2 = (Hello)h1.clone();
 h2.hello();
} catch (Exception e) {
    e.printStackTrace();
}
// 形式五: 通过序列化创立

//把内存中对象的状态转换为字节码的模式
//把字节码通过IO输入流,写到磁盘上
//永恒保留下来,长久化
//反序列化
//将长久化的字节码内容,通过IO输出流读到内存中来
//转化成一个Java对象

Hello hello = new Hello();
File file = new File("hello-serializable");
try {
    FileOutputStream fileOutputStream = new FileOutputStream(file);
 ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
 FileInputStream fileInputStream = new FileInputStream(file);
 ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
 objectOutputStream.writeObject(hello);
 Hello h = (Hello) objectInputStream.readObject();
 h.hello();
} catch (Exception e) {
    e.printStackTrace();
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理