首页 > 编程 > Java > 正文

JAVA中创建对象的四种方式

2019-11-08 01:59:34
字体:
来源:转载
供稿:网友
/** * <p> * Title: 创建对象的四种方式 * </p> *  *  * @author lwx * @version 1.0 * @create 2013 1 17 14:03:35 */public class CreateObj implements Cloneable,Serializable{    PRivate static String filename = CreateObj.class.getResource("").getPath()            + "/obj.txt";    static File file = new File(filename);    static {        if (!file.exists())            try {                file.createNewFile();            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }    }    public static void main(String[] args) throws Exception {        // 1.第一种常用方式        CreateObj s1 = new CreateObj();        System.out.println(s1);        // 2.第二种方式 静态方式 java.lang.InstantiationException        CreateObj s2 = (CreateObj) Class.forName(                "com.newland.commons.collectionutil.CreateObj").newInstance();        System.out.println(s2);        //第三种方式 用对象流来实现 前提是对象必须实现 Serializable        ObjectOutputStream objectOutputStream = new ObjectOutputStream(                new FileOutputStream(filename));        objectOutputStream.writeObject(s2);        ObjectInput input=new ObjectInputStream(new FileInputStream(filename));        CreateObj s3 = (CreateObj) input.readObject();        System.out.println(s3);        //第四种 clone 必须 实现Cloneable接口 否则抛出CloneNotSupportedException        CreateObj obj=new CreateObj();        CreateObj s4= (CreateObj) obj.clone();        System.out.println(s4);    }

}

作为java开发者,我们每天创建很多对象,但是我们通常使用依赖注入的方式管理系统,比如:Spring去创建对象,然而这里有很多创建对象的方法:使用New关键字、使用Class类的newInstance方法、使用Constructor类的newInstance方法、使用Clone方法、使用反序列化。

使用new关键字:这是我们最常见的也是最简单的创建对象的方式,通过这种方式我们还可以调用任意的够赞函数(无参的和有参的)。比如:Student student = new Student();使用Class类的newInstance方法:我们也可以使用Class类的newInstance方法创建对象,这个newInstance方法调用无参的构造器创建对象,如:Student student2 = (Student)Class.forName("根路径.Student").newInstance(); 或者:Student stu = Student.class.newInstance();使用Constructor类的newInstance方法:次方法和Class类的newInstance方法很像,java.lang.relect.Constructor类里也有一个newInstance方法可以创建对象。我们可以通过这个newInstance方法调用有参数的和私有的构造函数。如: Constructor<Student> constructor = Student.class.getInstance(); Student stu = constructor.newInstance(); 这两种newInstance的方法就是大家所说的反射,事实上Class的newInstance方法内部调用Constructor的newInstance方法。这也是众多框架Spring、Hibernate、Struts等使用后者的原因。使用Clone的方法:无论何时我们调用一个对象的clone方法,JVM就会创建一个新的对象,将前面的对象的内容全部拷贝进去,用clone方法创建对象并不会调用任何构造函数。要使用clone方法,我们必须先实现Cloneable接口并实现其定义的clone方法。如:Student stu2 = <Student>stu.clone();这也是原型模式的应用。使用反序列化:当我们序列化和反序列化一个对象,JVM会给我们创建一个单独的对象,在反序列化时,JVM创建对象并不会调用任何构造函数。为了反序列化一个对象,我们需要让我们的类实现Serializable接口。如:ObjectInputStream in = new ObjectInputStream (new FileInputStream("data.obj")); Student stu3 = (Student)in.readObject();

 

  从上面的例子可以看出来,除了使用new关键字之外的其他方法全部都是转变为invokevirtual(创建对象的直接方法),使用被new的方式转变为两个调用,new和invokespecial(构造函数调用)。 


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表