Home > OS >  How to create instance with Lombok with extend field
How to create instance with Lombok with extend field

Time:10-07

I have next problem. I have this method:

    public void sendDeletedEvent(final Comment comment) {
        log.info("SendDeletedEvent.E with Comment: {}", comment);
        final CommentDTO commentDTO = commentMapper.toDTO(comment);
        final CommentDeleteEvent commentDeleteEvent =  new CommentDeleteEvent(commentDTO);
        kafkaTemplate.send(commentEventTopic, commentDeleteEvent);
        log.info("SendDeleteEvent.X with CommentDeleteEvent : {}", commentDeleteEvent);
    }

and I want to replace all new creation on lombok builder, but I have some problem. This is my CommentDeleteEvent class:

@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@NoArgsConstructor
@Builder
@Data
public class CommentDeleteEvent extends AbstractCommentEvent {
    public CommentDeleteEvent(CommentDTO comment) {
        super(DELETE, comment);
    }
}

and abstractEvent

@EqualsAndHashCode(callSuper = true)
@Data
@Builder
@ToString
@AllArgsConstructor
@NoArgsConstructor
public abstract class AbstractCommentEvent extends AbstractEvent {
    private CommentDTO comment;

    public AbstractCommentEvent(EventType eventType, CommentDTO comment) {
        super(eventType);
        this.comment = comment;
    }
}

So when I try to build, builder don`t see abstract CommentDTO field, what I should to do? I can do next code, but I think that is bad idea:

        log.info("SendDeletedEvent.E with Comment: {}", comment);
        final CommentDTO commentDTO = commentMapper.toDTO(comment);
        final CommentDeleteEvent commentDeleteEvent = (CommentDeleteEvent) AbstractCommentEvent.builder()
                                                                                               .comment(commentDTO)
                                                                                               .build();
        kafkaTemplate.send(commentEventTopic, commentDeleteEvent);
        log.info("SendDeleteEvent.X with CommentDeleteEvent : {}", commentDeleteEvent);

What I should to do, or my idea is not wortest?)

CodePudding user response:

What you would want to use is @SuperBuilder instead of @Builder. @SuperBuilder works with fields from superclasses. This annotation should be added to both super and sub classes as well.

Also, we can not call a builder on an abstract superclass for obvious reasons. The builder has no way to know which subclass to instantiate. This is not a limitation of Lombok, this is how OOP works.

Because of this, we should invoke the builder as follows:

final CommentDeleteEvent commentDeleteEvent = CommentDeleteEvent.builder()
                                              .comment(commentDTO)                                                                                      
                                              .build();
  • Related