先创建一个实体类
```java
public class dog {
private String name;
private Integer age;
}
```
无参、带参构造方法、getter/setter方法、toString()方法都要写
## 使用new关键字
```java
dog d1 = new dog("小花",2);
```
## 使用反射
```java
//1. 使用无参构造方法
dog d2 = (dog) Class.forName("pojo").newInstance();
d2.setName("小黑");
d2.setAge(2);
//2. 使用带参构造方法
Class cls = Class.forName("dog");
Constructor cons =
cls.getConstructor(String.class, Integer.class);
dog d3 = (pojo) constructor.newInstance("小红", 3);
```
## 使用clone()方法
使用clone()方法需要让**dog**类实现Cloneable接口,并重写clone()方法
```java
public class dog implement Cloneable{
private String name;
private Integer age;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
```
实现clone
```java
//1. 不会生成新的对象
dog p4 = p1;
System.out.println(d4 == d1);//true
//2. 会在内存中生成新的dog对象
dog d5 = (dog)d1.clone();
System.out.println(d4 == d1);//false
```
## 使用序列化
使dog类能被序列化必须实现Serializable接口
```java
public class pojo implements Cloneable, Serializable {
}
```
```java
//1. 将对象序列化
dog d6 = new dog("小序",2);
ObjectOutputStream oos =
new ObjectOutputStream(newFileOutputStream("dog.txt"));
oos.writeObject(d6);
//2. 反序列化
ObjectInputStream ois =
new ObjectInputStream(new FileInputStream("dog.txt"));
pojo p6 = (pojo) ois.readObject();
```