• 面试Tip--java创建对象的四种方式


           java创建对象一共有四种方式,但是我们在写代码的时候用的new 关键字偏多,像一些接口对接则是序列化创建对象偏多,今天我们来简单介绍下使用场景以及各个方式

    1. 使用 new 关键字

            这是最常见的创建对象的方式。

    1. public class Example {
    2. private String message;
    3. public Example(String message) {
    4. this.message = message;
    5. }
    6. public String getMessage() {
    7. return message;
    8. }
    9. public static void main(String[] args) {
    10. Example example = new Example("Hello, World!");
    11. System.out.println(example.getMessage());
    12. }
    13. }
    2. 使用反射机制

            反射机制允许在运行时动态地创建对象、调用方法和访问字段。它通常用于框架和库中,提供高度的灵活性。

    优点

    • 动态性:可以在运行时加载和使用类,而无需在编译时知道具体的类。
    • 灵活性:可以动态调用类的方法和访问字段。

    缺点

    • 性能开销:反射操作通常比直接调用慢。
    • 安全性:可能破坏封装性,访问私有字段和方法可能带来安全隐患。

    使用场景

            ORM框架,SpringMVC使用@RequestBody这类的注解等等

    示例

    1. import java.lang.reflect.Constructor;
    2. import java.lang.reflect.Field;
    3. import java.lang.reflect.Method;
    4. public class ReflectionExample {
    5. private String message;
    6. public ReflectionExample(String message) {
    7. this.message = message;
    8. }
    9. public String getMessage() {
    10. return message;
    11. }
    12. public static void main(String[] args) {
    13. try {
    14. Class clazz = Class.forName("ReflectionExample");
    15. Constructor constructor = clazz.getConstructor(String.class);
    16. Object instance = constructor.newInstance("Hello, Reflection!");
    17. Method getMessageMethod = clazz.getMethod("getMessage");
    18. String message = (String) getMessageMethod.invoke(instance);
    19. System.out.println("Message: " + message);
    20. Field messageField = clazz.getDeclaredField("message");
    21. messageField.setAccessible(true);
    22. messageField.set(instance, "New Message via Reflection");
    23. System.out.println("Updated Message: " + getMessageMethod.invoke(instance));
    24. } catch (Exception e) {
    25. e.printStackTrace();
    26. }
    27. }
    28. }
    3. 使用 clone() 方法

    通过 clone() 方法可以创建一个对象的副本。需要实现 Cloneable 接口并重写 clone() 方法。

    1. public class Example implements Cloneable {
    2. private String message;
    3. public Example(String message) {
    4. this.message = message;
    5. }
    6. public String getMessage() {
    7. return message;
    8. }
    9. @Override
    10. protected Object clone() throws CloneNotSupportedException {
    11. return super.clone();
    12. }
    13. public static void main(String[] args) {
    14. try {
    15. Example original = new Example("Hello, World!");
    16. Example clone = (Example) original.clone();
    17. System.out.println(clone.getMessage());
    18. } catch (CloneNotSupportedException e) {
    19. e.printStackTrace();
    20. }
    21. }
    22. }
    4. 使用序列化与反序列化

            通过将对象序列化为字节流,然后再从字节流中反序列化,可以创建对象。这通常用于对象的持久化和传输。

    优点

    • 持久化:可以将对象的状态保存到文件或数据库中。
    • 传输:支持在网络上传输对象。
    • 深度复制:通过序列化和反序列化可以实现对象的深度复制。

    缺点

    • 性能开销:序列化和反序列化过程可能比较耗时。
    • 安全性:反序列化不可信数据可能带来安全风险。

    使用场景

    • 调用接口:我们开发的时候调用第三方接口,从三方接口获取的比如body的返回值,获取到的是String类型的,要不就是我们一层一层拨数据,要不就是反序列化对象
    • 数据库对象存储: 假设我们有一条订单表,这是假设,哥们不是做电商行业的。这张表有一个订单状态,那么我们就可以有一个长字段用来存储他的关系,而不是挂一张外表进行了。这里只是举例

    示例、

    1. import java.io.*;
    2. public class SerializationExample implements Serializable {
    3. private static final long serialVersionUID = 1L;
    4. private String message;
    5. public SerializationExample(String message) {
    6. this.message = message;
    7. }
    8. public String getMessage() {
    9. return message;
    10. }
    11. public static void main(String[] args) {
    12. SerializationExample original = new SerializationExample("Hello, Serialization!");
    13. // 序列化
    14. try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.dat"))) {
    15. oos.writeObject(original);
    16. } catch (IOException e) {
    17. e.printStackTrace();
    18. }
    19. // 反序列化
    20. try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.dat"))) {
    21. SerializationExample deserialized = (SerializationExample) ois.readObject();
    22. System.out.println("Deserialized Message: " + deserialized.getMessage());
    23. } catch (IOException | ClassNotFoundException e) {
    24. e.printStackTrace();
    25. }
    26. }
    27. }
     4.1使用 JSON 反序列化

    通过 JSON 反序列化,可以将 JSON 数据转换为 Java 对象,常用的库有 Jackson 和 Gson。

    1. import com.fasterxml.jackson.databind.ObjectMapper;
    2. import java.io.IOException;
    3. public class User {
    4. private String name;
    5. private int age;
    6. private String email;
    7. // Getters and Setters
    8. public static void main(String[] args) {
    9. String jsonString = "{\"name\":\"John\",\"age\":30,\"email\":\"john@example.com\"}";
    10. ObjectMapper objectMapper = new ObjectMapper();
    11. try {
    12. User user = objectMapper.readValue(jsonString, User.class);
    13. System.out.println("Name: " + user.getName());
    14. System.out.println("Age: " + user.getAge());
    15. System.out.println("Email: " + user.getEmail());
    16. } catch (IOException e) {
    17. e.printStackTrace();
    18. }
    19. }
    20. public String getName() {
    21. return name;
    22. }
    23. public void setName(String name) {
    24. this.name = name;
    25. }
    26. public int getAge() {
    27. return age;
    28. }
    29. public void setAge(int age) {
    30. this.age = age;
    31. }
    32. public String getEmail() {
    33. return email;
    34. }
    35. public void setEmail(String email) {
    36. this.email = email;
    37. }
    38. }

    ·通过上面的例子,这样我们在创建对象的时候就会更加清晰了

    点个关注再走吧!!!

  • 相关阅读:
    在 SQL Server 中使用 Try Catch 处理异常
    数学术语之源——群同态的“核(kernel)”
    新人如何做好功能测试,学会这几项够用了
    HTML制作个人网页制作(简单静态HTML个人博客网页作品)
    redis优势以及数据结构相关知识
    (27)Blender源码分析之顶层菜单的关于对话框
    java毕业设计开题报告SSM实现的在线音乐歌曲网站音乐播放器
    halcon 2D模板匹配 3D
    【SSL证书安全】
    贴片电阻材质:了解电子元件的核心构成 | 百能云芯
  • 原文地址:https://blog.csdn.net/weixin_45075231/article/details/139416312