美文网首页
@Builder注解加到类上时程序找不到类的无参构造方法

@Builder注解加到类上时程序找不到类的无参构造方法

作者: tomorrowsg | 来源:发表于2019-05-11 14:25 被阅读0次
@Data
@Builder
public class Student {
    private Long id;
    private String name;
    private String teacherName;
    private String className;
    private String schoolName;
}

上面等价于

@Data
public class Student {
    private Long id;
    private String name;
    private String teacherName;
    private String className;
    private String schoolName;

    @Builder
    public Student(Long id, String name, String teacherName, String className, String schoolName) {
        this.id = id;
        this.name = name;
        this.teacherName = teacherName;
        this.className = className;
        this.schoolName = schoolName;
    }
}

@Builder注解修饰类时,该类将没有无参构造方法

对于如下这种需要json字符串转换为实体类的情况,将报错

String studentJson = "{\"id\": 122456,\"name\": \"张三\",\"teacherName\": \"李四\",\"className\": \"高一\",\"schoolName\": \"一中\"}";
//将会报错com.alibaba.fastjson.JSONException: default constructor not found
Student student = JSON.parseObject(studentJson, new TypeReference<Student>(){});
System.out.println(JSON.toJSONString(student));

解决办法如下

第一种方法:Student加连个注解@NoArgsConstructor和@AllArgsConstructor

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Student {
    private Long id;
    private String name;
    private String teacherName;
    private String className;
    private String schoolName;
}

第二种方法:

@Data
public class Student {
    private Long id;
    private String name;
    private String teacherName;
    private String className;
    private String schoolName;

    @Builder
    public Student() {
    }

    @Builder
    public Student(Long id, String name, String teacherName, String className, String schoolName) {
        this.id = id;
        this.name = name;
        this.teacherName = teacherName;
        this.className = className;
        this.schoolName = schoolName;
    }
}

相关文章

网友评论

      本文标题:@Builder注解加到类上时程序找不到类的无参构造方法

      本文链接:https://www.haomeiwen.com/subject/besxaqtx.html