1、使用new关键字
2、利用反射手段,调用java.lang.Class或者java.lang.reflect.Constructor类的newInstance()实例方法
3、构造函数的newInstance()方法
4、对象的反序列化
5、对象的clone()方法
下面详细看看这5种方法的简单实现:
1、使用new关键字
public classTest {privateString name;publicTest() {
}publicTest(String name) {this.name =name;
}publicString getName() {returnname;
}public voidsetName(String name) {this.name =name;
}public static voidmain(String[] args) {
Test t1= newTest();
Test t2= new Test("张三");
}
}
2、利用反射
首先通过Class.forName()动态加载类的class对象,然后通过newInstance()方法获得Test对象,这里使用的是上面的Test对象
public static void main(String[] args) throwsException{
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) throwsException {
Constructorconstructor;try{
constructor= Test.class.getConstructor();
Test t=constructor.newInstance();
}catch (InstantiationException |IllegalAccessException|IllegalArgumentException|InvocationTargetException|NoSuchMethodException|SecurityException e) {
e.printStackTrace();
}
}
4、对象反序列化
继承Serializable接口
public class Test implementsSerializable{privateString name;publicTest() {
}publicTest(String name) {this.name =name;
}publicString getName() {returnname;
}public voidsetName(String name) {this.name =name;
}public static void main(String[] args) throwsException {
String filePath= "sample.txt";
Test t1= new Test("张三");try{
FileOutputStream fileOutputStream=
newFileOutputStream(filePath);
ObjectOutputStream outputStream=
newObjectOutputStream(fileOutputStream);
outputStream.writeObject(t1);
outputStream.flush();
outputStream.close();
FileInputStream fileInputStream=
newFileInputStream(filePath);
ObjectInputStream inputStream=
newObjectInputStream(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) throwsException {
Test t1= new Test("张三");
Test t2=(Test) t1.clone();
System.out.println(t2.getName());
}