1、使用new关键字
2、利用反射手段,调用java.lang.Class或者java.lang.reflect.Constructor类的newInstance()实例方法
3、构造函数的newInstance()方法
4、对象的反序列化
5、对象的clone()方法
下面详细看看这5种方法的简单实现:
1、使用new关键字
public class Test { private String name; public Test() { } public Test(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public static void main(String[] args) { Test t1 = new Test(); Test t2 = new Test("张三"); } }
2、利用反射
首先通过Class.forName()动态加载类的class对象,然后通过newInstance()方法获得Test对象,这里使用的是上面的Test对象
public static void main(String[] args) throws Exception{ String className="com.qml.test"; Class clasz=Class.forName(className); Test t=(Test)clasz.newInstance(); }
3、构造函数对象的newInstance()方法
类Constructor也有newInstance方法,这一点和Class有点像。从它的名字可以看出它与Class的不同,Class是通过类来创建对象,而Constructor则是通过构造器。依然使用第一个例子中的Test类。
public static void main(String[] args) throws Exception { Constructor<Test> constructor; try { constructor = Test.class.getConstructor(); Test t = constructor.newInstance(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { e.printStackTrace(); } }
4、对象反序列化
继承Serializable接口
public class Test implements Serializable{ private String name; public Test() { } public Test(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public static void main(String[] args) throws Exception { String filePath = "sample.txt"; Test t1 = new Test("张三"); try { FileOutputStream fileOutputStream = new FileOutputStream(filePath); ObjectOutputStream outputStream = new ObjectOutputStream(fileOutputStream); outputStream.writeObject(t1); outputStream.flush(); outputStream.close(); FileInputStream fileInputStream = new FileInputStream(filePath); ObjectInputStream inputStream = new ObjectInputStream(fileInputStream); Test t2 = (Test) inputStream.readObject(); inputStream.close(); System.out.println(t2.getName()); } catch (Exception ee) { ee.printStackTrace(); } } }
5、对象的clone()方法
public static void main(String[] args) throws Exception { Test t1 = new Test("张三"); Test t2 = (Test) t1.clone(); System.out.println(t2.getName()); }
原文:https://www.cnblogs.com/qml0725/p/13276510.html