/*
* 实例化对象的几种方式
* 1. new
* 2. 通过工厂方法返回对象
* 3. 调用对象的clone方法
* 4. 反射
* 5. 反序列化
* */
直接从第二种开始
1 /**
2 * 2工厂
3 */
4 String str = String.valueOf(23);
5 System.out.println(str);
6 /**
7 * 3.克隆方法 需要实现Cloneable接口和重写clone方法
8 */
9
10 Person p = new Person();
11 p.setName("haha");
12 p.setAge(11);
13 Person pClone = (Person) p.clone();
14 System.out.println(p);
15 System.out.println(pClone);
16 /**
17 * 4.反射
18 * 反射1. Class类的newInstance方法,空参构造没有被私有化
19 */
20 Class<Person> c = Person.class;
21 Person p = c.newInstance();
22 p.setName("zhsangsan");
23 p.setAge(23);
24 System.out.println(p);
25
26 //反射2 Class的getConstructor()获取构造器,调用Constructor的newInstance方法 构造方法也不能被私有化
27 Constructor<Person> constructor = c.getConstructor();
28 Person p2 = constructor.newInstance();
29 p2.setName("lisi");
30 p2.setAge(21);
31 System.out.println(p2);
32
33 //反射3 构造方法被私有化 多一步,申请访问
34 Constructor<Person> con = c.getDeclaredConstructor();
35 con.setAccessible(true);
36 Person p3 = con.newInstance();
37 p3.setName("wangwu");
38 p3.setAge(25);
39 System.out.println(p3);
40 /**
41 * 5.反序列化
42 * 条件:实现Serilizable接口
43 */
44
45 //需要序列化的对象
46 Person p = new Person("吴慷仁",54);
47 //序列化到磁盘"G:seri.txt"
48 ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("G:\seri.txt"));
49 //写入数据
50 out.writeObject(p);
51 out.writeObject("美丽");
52 out.writeObject(new Date());
53 out.writeObject(123);
54 out.close();
55
56 //2.反序列化创建对象
57 ObjectInputStream in = new ObjectInputStream(new FileInputStream("G:\seri.txt"));
58 Person obj1 = (Person)in.readObject();
59 String obj2 = (String)in.readObject();
60 Date obj3 = (Date)in.readObject();
61 int obj4 = (int)in.readObject();
62 System.out.println("String类" + obj2 + " " + "Date类" + obj3 + " " + "Person类" + obj1 + " "
63 + "int类" + obj4);
64 in.close();