Adrian Herscu
Adrian Herscu

Reputation: 817

lombok builder around existing data value class

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?

Upvotes: 6

Views: 1628

Answers (1)

Michael Piefel
Michael Piefel

Reputation: 19998

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());

Upvotes: 1

Related Questions