java创建对象一共有四种方式,但是我们在写代码的时候用的new 关键字偏多,像一些接口对接则是序列化创建对象偏多,今天我们来简单介绍下使用场景以及各个方式
new
关键字这是最常见的创建对象的方式。
- public class Example {
- private String message;
-
- public Example(String message) {
- this.message = message;
- }
-
- public String getMessage() {
- return message;
- }
-
- public static void main(String[] args) {
- Example example = new Example("Hello, World!");
- System.out.println(example.getMessage());
- }
- }
反射机制允许在运行时动态地创建对象、调用方法和访问字段。它通常用于框架和库中,提供高度的灵活性。
优点
缺点
使用场景
ORM框架,SpringMVC使用@RequestBody这类的注解等等
示例
- import java.lang.reflect.Constructor;
- import java.lang.reflect.Field;
- import java.lang.reflect.Method;
-
- public class ReflectionExample {
- private String message;
-
- public ReflectionExample(String message) {
- this.message = message;
- }
-
- public String getMessage() {
- return message;
- }
-
- public static void main(String[] args) {
- try {
- Class> clazz = Class.forName("ReflectionExample");
-
- Constructor> constructor = clazz.getConstructor(String.class);
- Object instance = constructor.newInstance("Hello, Reflection!");
-
- Method getMessageMethod = clazz.getMethod("getMessage");
- String message = (String) getMessageMethod.invoke(instance);
- System.out.println("Message: " + message);
-
- Field messageField = clazz.getDeclaredField("message");
- messageField.setAccessible(true);
- messageField.set(instance, "New Message via Reflection");
- System.out.println("Updated Message: " + getMessageMethod.invoke(instance));
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
clone()
方法通过 clone()
方法可以创建一个对象的副本。需要实现 Cloneable
接口并重写 clone()
方法。
- public class Example implements Cloneable {
- private String message;
-
- public Example(String message) {
- this.message = message;
- }
-
- public String getMessage() {
- return message;
- }
-
- @Override
- protected Object clone() throws CloneNotSupportedException {
- return super.clone();
- }
-
- public static void main(String[] args) {
- try {
- Example original = new Example("Hello, World!");
- Example clone = (Example) original.clone();
- System.out.println(clone.getMessage());
- } catch (CloneNotSupportedException e) {
- e.printStackTrace();
- }
- }
- }
通过将对象序列化为字节流,然后再从字节流中反序列化,可以创建对象。这通常用于对象的持久化和传输。
优点
缺点
使用场景
示例、
- import java.io.*;
-
- public class SerializationExample implements Serializable {
- private static final long serialVersionUID = 1L;
- private String message;
-
- public SerializationExample(String message) {
- this.message = message;
- }
-
- public String getMessage() {
- return message;
- }
-
- public static void main(String[] args) {
- SerializationExample original = new SerializationExample("Hello, Serialization!");
-
- // 序列化
- try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.dat"))) {
- oos.writeObject(original);
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- // 反序列化
- try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.dat"))) {
- SerializationExample deserialized = (SerializationExample) ois.readObject();
- System.out.println("Deserialized Message: " + deserialized.getMessage());
- } catch (IOException | ClassNotFoundException e) {
- e.printStackTrace();
- }
- }
- }
通过 JSON 反序列化,可以将 JSON 数据转换为 Java 对象,常用的库有 Jackson 和 Gson。
- import com.fasterxml.jackson.databind.ObjectMapper;
- import java.io.IOException;
-
- public class User {
- private String name;
- private int age;
- private String email;
-
- // Getters and Setters
-
- public static void main(String[] args) {
- String jsonString = "{\"name\":\"John\",\"age\":30,\"email\":\"john@example.com\"}";
-
- ObjectMapper objectMapper = new ObjectMapper();
- try {
- User user = objectMapper.readValue(jsonString, User.class);
- System.out.println("Name: " + user.getName());
- System.out.println("Age: " + user.getAge());
- System.out.println("Email: " + user.getEmail());
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public int getAge() {
- return age;
- }
-
- public void setAge(int age) {
- this.age = age;
- }
-
- public String getEmail() {
- return email;
- }
-
- public void setEmail(String email) {
- this.email = email;
- }
- }
·通过上面的例子,这样我们在创建对象的时候就会更加清晰了
点个关注再走吧!!!