Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lombok builder around existing data value class

Tags:

java

lombok

Having a library provided class such as org.springframework.security.oauth2.provider.client.BaseClientDetails I would like to have it wrapped as a Lombok (or similar) builder.

Currently, I derived a wrapper class like this:

public static final class BaseClientDetailsWrapper
    extends BaseClientDetails {
    @Builder
    private BaseClientDetailsWrapper(
        final String clientId,
        final List<String> resourceIds,
        final List<GrantedAuthority> suthorities,
        final List<String> scopes,
        final List<String> autoApproveScopes,
        final List<String> authorizedGrantTypes,
        final String clientSecret) {
        super();
        setClientId(clientId);
        setResourceIds(resourceIds);
        setAuthorities(authorities);
        setScope(scopes);
        setAuthorizedGrantTypes(authorizedGrantTypes);
        setAutoApproveScopes(autoApproveScopes);
        setClientSecret(clientSecret);
    }
}

Is there a way to get rid of the annoying setXxx(...) code?

like image 538
Adrian Herscu Avatar asked Nov 09 '22 02:11

Adrian Herscu


1 Answers

Isn’t there a constructor that more closely meets your needs? No, there is no way to ask Lombok to consider some other function as your builder template that is not under your control.


As a side note, there is no need to sub-class the BaseClientDetails. You can put @Builder on any function, no matter what class it is in. The following is perfectly acceptable:

@Builder(builderMethodName = "fullname")
private static String fullnameHelper(String forename, String middle, String surname) {
    Objects.requireNonNull(forename);
    Objects.requireNonNull(surname);
    return forename + " " + (middle == null ? "" : middle + " ") + surname;
}

The name of the method does not matter at all. Hide it away privately in a utility class, if you want. You can use it as such:

fullname().forename("Alan").surname("Turing").build());
fullname().forename("Donald").middle("E.").surname("Knuth").build());
like image 189
Michael Piefel Avatar answered Nov 15 '22 07:11

Michael Piefel