Reputation: 11091
I have a simple dto
class
@Getter
@EqualsAndHashCode
@ToString
@RequiredArgsConstructor(staticName = "of", access = AccessLevel.PUBLIC)
public class MyClass {
private final String field1;
private final String field2;
}
I need to have both constructors static
and non-static
. If I delombok constructors
@Getter
@EqualsAndHashCode
@ToString
public class MyClass{
private final String field1;
private final String field2;
private MyClass(String field1, String field2) {
this.field1= field1;
this.field2= field2;
}
public static MyClass of(String field1, String field2) {
return new MyClass(field1, field2);
}
}
It's almost what I need but the non-static
constructor is private
. Is it possible to make it public
with lombok?
Upvotes: 4
Views: 4011
Reputation: 191
This is not possible in Lombok (at least not in the current version 1.18.12). Consider reviewing the JavaDoc here. It says that setting the staticName property will mark the constructor private. It does not specify explicitly that it will ignore the access property, but in practice it appears it does.
It is usually considered bad practice to provide multiple ways to achieve the same result, in this case creating a class instance with the same parameters. Given the fact that your code already uses both, you might consider creating the static builder methods manually and marking one technique as deprecated, to prevent its future use until completely refactoring it out.
@Getter
@EqualsAndHashCode
@ToString
@AllArgsConstructor(onConstructor=@__(@Deprecated))
public class MyClass {
private final String field1;
private final String field2;
public static MyClass of(String field1, String field2) {
return new MyClass(field1, field2);
}
}
or:
@Getter
@EqualsAndHashCode
@ToString
@AllArgsConstructor
public class MyClass {
private final String field1;
private final String field2;
/**
* @deprecated Will be removed in the future.
* Use {@link #MyClass(String, String)} instead
*/
@Deprecated
public static MyClass of(String field1, String field2) {
return new MyClass(field1, field2);
}
}
Upvotes: 1