当前位置: 代码网 > it编程>编程语言>Java > Java创建对象的六种常用方式总结

Java创建对象的六种常用方式总结

2024年07月03日 Java 我要评论
在java中,创建对象通常有以下几种方式:使用new关键字这是最常见的方式,通过调用类的构造函数来创建对象。public class myclass { int x; myclass(in

在java中,创建对象通常有以下几种方式:

使用new关键字

这是最常见的方式,通过调用类的构造函数来创建对象。

public class myclass {
    int x;

    myclass(int x) {
        this.x = x;
    }

    public static void main(string[] args) {
        myclass obj = new myclass(10); // 使用new关键字创建对象
        system.out.println(obj.x); // 输出: 10
    }
}

使用反射(reflection)

java的反射api允许你在运行时创建对象。

public class myclass {
    // ... 省略其他代码 ...

    public static void main(string[] args) throws exception {
        class<?> clazz = myclass.class;
        myclass obj = (myclass) clazz.getdeclaredconstructor(int.class).newinstance(20); // 使用反射创建对象
        system.out.println(obj.x); // 输出: 20
    }
}

注意:反射通常用于更高级的场景,因为它涉及到更多的错误检查和异常处理。

使用class.forname()与newinstance()(已过时)

虽然class.newinstance()方法在java 9中已被标记为过时,但在早期版本中,你可以使用它(与forname()结合)来创建对象。但是,由于它不支持带参数的构造函数,所以其用途有限。

// 注意:此方法在java 9+中已过时,不建议使用
public class myclass {
    // ... 省略其他代码 ...

    // 假设myclass有一个无参数的构造函数
    public static void main(string[] args) throws exception {
        myclass obj = (myclass) class.forname("myclass").newinstance(); // 使用class.forname和newinstance创建对象
        // 注意:这种方法不支持带参数的构造函数
    }
}

使用反序列化(deserialization)

如果你的对象之前已经被序列化(写入到一个输出流中),你可以通过反序列化来创建它的一个新实例。

import java.io.*;

public class myclass implements serializable {
    // ... 省略其他代码和序列化id ...

    public static void main(string[] args) throws exception {
        // 假设我们有一个包含myclass对象的文件
        fileinputstream fis = new fileinputstream("myfile.ser");
        objectinputstream ois = new objectinputstream(fis);
        myclass obj = (myclass) ois.readobject(); // 通过反序列化创建对象
        ois.close();
        fis.close();
        // 现在你可以使用obj了
    }
}

使用工厂方法(factory method)

下滑查看解决方法

工厂方法是一种设计模式,它使用静态方法来创建对象。这通常用于封装对象的创建逻辑,以便在需要时可以更改它。

public class myclass {
    // ... 省略其他代码 ...

    public static myclass createinstance(int x) {
        return new myclass(x); // 使用工厂方法创建对象
    }

    public static void main(string[] args) {
        myclass obj = myclass.createinstance(30); // 使用工厂方法创建对象
        system.out.println(obj.x); // 输出: 30
    }
}

使用克隆(clone)

如果你已经有一个对象,并且想要创建它的一个精确副本,你可以使用clone()方法(但需要注意的是,它默认是浅拷贝,且需要实现cloneable接口)。

public class myclass implements cloneable {
    int x;

    // ... 省略其他代码 ...

    @override
    protected myclass clone() throws clonenotsupportedexception {
        return (myclass) super.clone(); // 使用clone方法创建对象的副本
    }

    public static void main(string[] args) throws clonenotsupportedexception {
        myclass original = new myclass(40);
        myclass copy = original.clone(); // 使用clone方法创建对象的副本
        system.out.println(copy.x); // 输出: 40
    }
}

注意:虽然上述方法都可以用来创建对象,但在实际项目中,最常用的还是使用new关键字和工厂方法。其他方法通常用于更高级或特定的场景。

附:示例代码(全)

以下是本文所用到的所有示例代码。

编写student学生类

package com.effective.chapter2.other;
 
import lombok.allargsconstructor;
import lombok.data;
import lombok.noargsconstructor;
 
import java.io.serializable;
 
@data
@allargsconstructor
@noargsconstructor
public class student implements cloneable, serializable {
    private string name;
    private integer age;
 
    @override
    public student clone() {
        try {
            student clone = (student) super.clone();
            // todo: copy mutable state here, so the clone can't change the internals of the original
            return clone;
        } catch (clonenotsupportedexception e) {
            throw new assertionerror();
        }
    }
}

编写测试类

package com.effective.chapter2.other;
 
import java.io.*;
import java.lang.reflect.constructor;
 
public class createobjecttest {
 
    private static final string file_name = "student.obj";
 
    public static void main(string[] args) throws instantiationexception, illegalaccessexception, ioexception {
 
        // 1、使用new关键字创建对象
        student student1 = new student();
        system.out.println("使用new关键字创建对象:" + student1);
 
        // 2、使用class类的newinstance()方法创建对象
        student student2 = student.class.newinstance();
        system.out.println("使用class类的newinstance()方法创建对象:" + student2);
 
        // 3、使用constructor类的newinstance()方法创建对象
        constructor student3 = constructor.class.newinstance();
        system.out.println("使用constructor类的newinstance()方法创建对象:" + student3);
 
        // 4、使用clone()方法创建对象
        student student4 = student2.clone();
        system.out.println("使用clone()方法创建对象:" + student4);
 
        try {
            // java序列化是指把java对象转换为字节序列的过程,而java反序列化是指把字节序列恢复为java对象的过程;
            // 序列化对象
            objectoutputstream oos = new objectoutputstream(new fileoutputstream(file_name));
            oos.writeobject(student1);
 
            objectinputstream ois = new objectinputstream(new fileinputstream(file_name));
            // 5、使用反序列化创建对象
            object student5 = ois.readobject();
            system.out.println("使用反序列化创建对象:" + student5);
        } catch (classnotfoundexception e) {
            throw new runtimeexception(e);
        }
    }
}

总结

到此这篇关于java创建对象的六种常用方式总结的文章就介绍到这了,更多相关java创建对象方式内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com