Here's code
public Configuration setProperty(int someSpecificProperty) {
MyAppUtil.requirePositive(someSpecificProperty, "someSpecificProperty");
this.someSpecificProperty = someSpecificProperty;
return this;
}
// MyAppUtil
static void requirePositive(int property, String propertyName) {
if (property <= 0) {
throw new IllegalPropertyException(propertyName, PropertyIssue.NON_POSITIVE);
}
}
public class IllegalPropertyException extends RuntimeException {
private static final String FORMAT = "%s value is invalid: should be %s";
public IllegalPropertyException(String propertyName, PropertyIssue propertyIssue) {
super(String.format(FORMAT, propertyName, propertyIssue.whatItShouldBeInstead()));
}
@RequiredArgsConstructor
public enum PropertyIssue {
NULL("not null"), EMPTY("not empty"), NON_POSITIVE("greater than zero");
private final String whatItShouldBeInstead;
String whatItShouldBeInstead() {
return whatItShouldBeInstead;
}
}
}
Notice how I pass both a property and that property's name. I am wondering whether I could get that information about the argument name dynamically so that the client (or rather, I) don't have to pass it manually each time. It would've been nice if I could call the requrePositive()
method like this (and MyAppUtil
figured out the argument name itself):
public Configuration setSpecificProperty(int someSpecificProperty) {
MyAppUtil.requirePositive(someSpecificProperty);
this.someSpecificProperty = someSpecificProperty;
return this;
}
Is there a way to do that?
Aucun commentaire:
Enregistrer un commentaire