1、使用new关键字
通过new关键字直接在堆内存上创建对象,这样很方便的调用对象的有参和无参的构造函数.
Student stu1 = new Student("lihua");
2、Class反射调用
使用Java中反射特性,来进行对象的创建。使用Class
类的newInstance
方法可以调用无参的构造器来创建对象,如果是有参构造器,则需要使用Class
的forName
方法和Constructor
来进行对象的创建。
Class stuClass = Class.forName("Student");
Constructor constructor = stuClass.getConstructor(String.class);
Student stu2 = (Student) constructor.newInstance("李四");
3、使用Clone方法
使用Clone的方法:无论何时我们调用一个对象的clone方法,JVM就会创建一个新的对象,将前面的对象的内容全部拷贝进去,用clone方法创建对象并不会调用任何构造函数。要使用clone方法,我们必须先实现Cloneable接口并实现其定义的clone方法。
try
{
Student stu3 = (Student) stu1.clone();
System.out.println(stu3);
}
catch (CloneNotSupportedException e)
{
e.printStackTrace();
}
4、使用序列化
一个对象实现了Serializable
接口,就可以把对象写入到文件中,并通过读取文件来创建对象。
String path = Test.class.getClassLoader().getResource("").getPath();
String objectFilePath = path + "out.txt";
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(objectFilePath));
objectOutputStream.writeObject(stu2);
ObjectInput objectInput = new ObjectInputStream(new FileInputStream(objectFilePath));
Student stu4 = (Student) objectInput.readObject();
示例代码
Student对象,实现Cloneable
和Serializable
接口
import java.io.Serializable;
/**
* Created by wzj on 2017/11/3.
*/
public class Student implements Cloneable,Serializable
{
private String name;
public Student(String name)
{
this.name = name;
}
/**
* @return a clone of this instance.
* @throws CloneNotSupportedException if the object's class does not
* support the {@code Cloneable} interface. Subclasses
* that override the {@code clone} method can also
* throw this exception to indicate that an instance cannot
* be cloned.
* @see Cloneable
*/
@Override
protected Object clone() throws CloneNotSupportedException
{
return super.clone();
}
}
测试类
import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
* Created by wzj on 2017/11/2.
*/
public class Test
{
public static void main(String[] args) throws Exception
{
//1、第一种方式是通过new
Student stu1 = new Student("lihua");
System.out.println(stu1);
//2、通过java反射,静态方式
Class stuClass = Class.forName("Student");
Constructor constructor = stuClass.getConstructor(String.class);
Student stu2 = (Student) constructor.newInstance("李四");
System.out.println(stu2);
//3、通过clone实现,必须实现Cloneable接口
try
{
Student stu3 = (Student) stu1.clone();
System.out.println(stu3);
}
catch (CloneNotSupportedException e)
{
e.printStackTrace();
}
//4、通过对象流,必须实现Serializable
String path = Test.class.getClassLoader().getResource("").getPath();
String objectFilePath = path + "out.txt";
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(objectFilePath));
objectOutputStream.writeObject(stu2);
ObjectInput objectInput = new ObjectInputStream(new FileInputStream(objectFilePath));
Student stu4 = (Student) objectInput.readObject();
System.out.println(stu4);
}