一、new关键字创建
UserInfo userInfo = new UserInfo();
二、Java的反射机制(通过newInstance)
1、class.forName 加载类
UserInfo userInfo = (UserInfo)Class.forName("com.ecreditpal.tzxyf.common.domain.model.cleaned.UserInfo").newInstance(); userInfo.setAge(1); System.out.println(userInfo);
2、XX.class.newInstance加载类
UserInfo info1 = UserInfo.class.newInstance(); info1.setAge(2); System.out.println(info1);
3、反序列化创建对象(底层也是使用的newInstance())
ObjectInputStream in = new ObjectInputStream(new FileInputStream("xxxx.txt")); UserInfo emp5 = (UserInfo) in.readObject(); emp5.setAge(3); System.out.println(emp5);
三、clone创建
使用clone创建,需要implements Cloneable
UserInfo info2 = (UserInfo) info1.clone1();
System.out.println(info2);