Demo代码地址
User.java
UserTest.java
User user = new User();
try { // 1.使用Class类的newInstance方法来创建对象 Class class1 = Class.forName("com.king.java_interview.java.a.User"); User user1 = (User) class1.newInstance(); user1.init("test1", "男", 12); System.out.println(user1); //或者 User user2 = User.class.newInstance(); // 2.使用Constructor类的newInstance方法来创建兑现 Class class2 = Class.forName("com.king.java_interview.java.a.User"); Constructor<User> constructor = class2.getConstructor(); User user3 = constructor.newInstance(); user3.init("test2", "男", 12); System.out.println(user3); } catch (ClassNotFoundException | InvocationTargetException | IllegalAccessException | InstantiationException | NoSuchMethodException e) { e.printStackTrace(); }
前提:使用Object
的clone
方法的前提是你的实体类必须实现了Cloneable
接口,重写Object的clone方法可以创建一个内存大小跟它一样大的对象
User user1 = new User(); user1.init("test1", "男", 12); User user2 = user1.clone(); System.out.println(user2); //这两个对象不是同一个对象 System.out.println(user1 == user2);
在通过实现序列化serializable接口将对象存到硬盘中,通过反序列化可以获取改对象
User user = new User(); user.init("king", "男", 12); //准备一个文件用于存储该对象的信息 File f = new File("hello.obj"); if (!f.exists()){ f.mkdirs(); } try (FileOutputStream fos = new FileOutputStream(f); ObjectOutputStream oos = new ObjectOutputStream(fos); FileInputStream fis = new FileInputStream(f); ObjectInputStream ois = new ObjectInputStream(fis) ) { //序列化对象,写入到磁盘中 oos.writeObject(user); //反序列化对象 User newUser = (User) ois.readObject(); //测试方法 newUser.println(); } catch (ClassNotFoundException | IOException e) { e.printStackTrace(); }