public static void main(String[] args) throws IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, CloneNotSupportedException { //1、使用关键字new创建对象(没有参数调用无参构造、传入参数调用带参构造) Girlfriend girlfriend01 = new Girlfriend(); Girlfriend girlfriend02 = new Girlfriend("y", 18); //2、使用反射机制创建对象,使用Class的newInstance()调用默认的无参构造 Girlfriend girlfriend03 = Girlfriend.class.newInstance(); //反射机制2,调用带参 Class<?> p1 = Class.forName("com.yky.Girlfriend"); Constructor<?> constructor = p1.getConstructor(String.class, Integer.class); Girlfriend girlfriend04 = (Girlfriend) constructor.newInstance("k", 18); System.out.println(girlfriend04); //3、使用object类的clone方法 Girlfriend girlfriendClone = (Girlfriend) girlfriend04.clone(); System.out.println("girlfriendClone="+girlfriendClone); //4、使用序列化反序列化生成对象 Girlfriend clone = ObjectUtils.clone(girlfriend04); System.out.println("clone"+clone); System.out.println("girlfriend04和反序列化生成的clone相等吗"); System.out.println(clone == girlfriend04); } |