在Java中创建对象的方式有以下几种:
ClassName obj = new ClassName();
Class clazz = Class.forName("ClassName");
ClassName obj = (ClassName) clazz.newInstance();
ClassName obj1 = new ClassName();
ClassName obj2 = (ClassName) obj1.clone();
// 序列化对象
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("filename"));
out.writeObject(obj);
out.close();
// 反序列化对象
ObjectInputStream in = new ObjectInputStream(new FileInputStream("filename"));
ClassName obj = (ClassName) in.readObject();
in.close();
public class ObjectFactory {
public static ClassName createObject() {
return new ClassName();
}
}
ClassName obj = ObjectFactory.createObject();
Supplier<ClassName> supplier = ClassName::new;
ClassName obj = supplier.get();