gpt4 book ai didi

java - Gson 不遵守生成器中的规则

转载 作者:行者123 更新时间:2023-11-30 08:04:28 24 4
gpt4 key购买 nike

我有一个名为 Student 的类,它有一些必填字段,其他字段是可选的。为确保在未提供必填字段的情况下不会创建类 Student 的对象,我使用了构建器。这是 Student 类:

package prj1.dob;

import java.util.Date;

public class Student {
private final int id;
private final String name;
private final String surname;
private final Date dob;
private final Double gpa;
private final String email;

public static class Builder {
//required fields
private int id;
private String name;
private String surname;

//optional fields
private Date dob;
private Double gpa;
private String email;

public Builder(int id, String name, String surname) {
this.id = id;
this.name = name;
this.surname = surname;
}

public Builder dob(Date dob) {
this.dob = dob;
return this;
}

public Builder gpa(Double gpa) {
this.gpa = gpa;
return this;
}

public Builder email(String email) {
this.email = email;
return this;
}

public Student build() throws Exception {
return new Student(this);
}
}

private Student(Builder b) throws Exception {
this.id = b.id;
this.name = b.name;
this.surname = b.surname;
this.dob = b.dob;
this.gpa = b.gpa;
this.email = b.email;
validate();
}

private void validate() throws Exception {
if (id < 10 || name == null || surname == null) {
throw new Exception("You should provide an id, name and surname.");
}
}

@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", surname=" + surname + ", dob=" + dob + ", gpa=" + gpa + ", email=" + email + "]";
}
}

有了 Student 类的这个实现,我希望不应该有创建无效 Student 对象的方法(即必填字段不应该是 )。但是,下面提供的代码不会抛出 Exception,当我打印 Student 的内容时,必填字段为 null

JSON 对象:

{"id":-1,"name":null,"surname":null,"dob":null,"gpa":null,"email":null}

这是从 JSON 创建 POJO 的代码:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String param = request.getParameter("std").toString();
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").serializeNulls().create();
Student student = gson.fromJson(param, Student.class);
// student.validate();
response.getWriter().write(student.toString());
} catch (Exception ex) {
response.getWriter().write(ex.getMessage());
}
}

我希望它会抛出一个Exception 但它创建了一个Student 的对象并且在打印时这是内容:

Student [id=-1, name=null, surname=null, dob=null, gpa=null, email=null]

这是 Gson 库中的错误还是我做错了什么?

如果这是应该的,那么在不遵守规则(提供必填字段)的情况下仍然可以创建类的对象时,使用构建器方法有什么意义?

最佳答案

GSON 使用 reflection而不是您的构建器来构建 Student

虽然您无法阻止 Student 的其他用户随意使用反射创建内容,但您可以提供 JsonDeserializer它知道 Student 的规则并使用您的构建器创建一个。

关于java - Gson 不遵守生成器中的规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35622872/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com