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

2次阅读

共计 1308 个字符,预计需要花费 4 分钟才能阅读完成。

一:创立一个测试实体

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();
}
正文完
 0