new关键字
Person person1 = new Person();
Person person2 = new Person("fsx", 18);
Class类的newInstance()使用的是类的public的无参构造器
Person person = Person.class.newInstance();
System.out.println(person); // Person{name='null', age=null}
Class的getDeclaredConstructors()可以调用无参、有参、私有的构造函数
Constructor<?>[] declaredConstructors = Person.class.getDeclaredConstructors();
Constructor<?> noArgsConstructor = declaredConstructors[0];
Constructor<?> haveArgsConstructor = declaredConstructors[1];
noArgsConstructor.setAccessible(true); // 非public的构造必须设置true才能用于创建实例
Object person1 = noArgsConstructor.newInstance();
Object person2 = haveArgsConstructor.newInstance("fsx", 18);
clone()方法
深拷贝,请参考Object常用方法讲解(附带使用示例)
// 对用对象的clone方法,并且重写clone方法
public class Person implements Cloneable {
@Override
public Person clone() throws CloneNotSupportedException {
return (Person) super.clone();
}
}
public static void main(String[] args) throws Exception {
Person person = new Person("fsx", 18);
Object clone = person.clone();
System.out.println(person == clone); //false
}
序列化创建对象
// 当我们序列化和反序列化一个对象,JVM会给我们创建一个单独的空间,用来存储该对象
// 需要让我们的类实现Serializable接口
Person person = new Person("fsx", 18);
byte[] bytes = SerializationUtils.serialize(person);
Object deserPerson = SerializationUtils.deserialize(bytes);
System.out.println(person == deserPerson); // false