作为Java开发者,我们每天创建很多对象,但我们通常使用依赖管理系统,比如Spring去创建对象。然而这里有很多创建对象的方法,我们会在这篇文章中学到。
Java中有5种创建对象的方式,下面给出它们的例子还有它们的字节码
使用new关键字 | 调用构造函数 |
使用class类的newInstance()方法 | 调用构造函数 |
使用Constructor类的newInstance()方法 | 调用构造函数 |
使用clone方法 | 没有调用构造函数 |
代码如下:
先建立Student类
public class Student implements Cloneable{
public void sayHello(){
System.out.println("hello!");
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
测试类:
public class Test{
//1、使用new关键字
public static void one(){
Student s1 = new Student();
s1.sayHello();
}
//2、使用newInstance方法
public static void two() throws Exception{
Student s2 = (Student)Class.forName("Student").newInstance();
s2.sayHello();
}
//3、使用newInstance方法
public static void three() throws Exception{
Student s3 = Student.class.newInstance();
s3.sayHello();
}
//4、使用Constructor类的newInstance方法
public static void four() throws Exception{
Constructor<Student> constructor = Student.class.getConstructor();
Student s4 = constructor.newInstance();
s4.sayHello();
}
//5、使用clone方法
public static void five() throws Exception{
Constructor<Student> constructor = Student.class.getConstructor();
Student s4 = constructor.newInstance();
Student s5 = (Student)s4.clone();
s5.sayHello();
}
public static void six() throws Exception{
}
public static void main(String[] args) throws Exception{
// one();
// two();
// three();
// four();
five();
}
}