Skip to content

Commit eae713b

Browse files
committed
Add getRequiredName and hasName API to org.springframework.data.mapping.Parameter.
Introduces a more convenient API to simplify the caller side especially for conditionals that want to determine whether a parameter name is present. Closes spring-projects#3088
1 parent c0b60b2 commit eae713b

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

Diff for: src/main/java/org/springframework/data/mapping/Parameter.java

+25
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,31 @@ public String getName() {
9999
return name;
100100
}
101101

102+
/**
103+
* Returns the required parameter name.
104+
*
105+
* @return the parameter name or throws {@link IllegalStateException} if the parameter does not have a name
106+
* @since 3.5
107+
*/
108+
public String getRequiredName() {
109+
110+
if (!hasName()) {
111+
throw new IllegalStateException("No name associated with this parameter");
112+
}
113+
114+
return getName();
115+
}
116+
117+
/**
118+
* Returns whether the parameter has a name.
119+
*
120+
* @return whether the parameter has a name
121+
* @since 3.5
122+
*/
123+
public boolean hasName() {
124+
return this.name != null;
125+
}
126+
102127
/**
103128
* Returns the {@link TypeInformation} of the parameter.
104129
*

Diff for: src/test/java/org/springframework/data/mapping/ParameterUnitTests.java

+29
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,35 @@ void shouldNotConsiderRecordMemberTypeOfClassEnclosingClassParameter() {
149149
assertThat(iFace.isEnclosingClassParameter()).isFalse();
150150
}
151151

152+
@Test // GH-3088
153+
void getRequiredNameDoesNotThrowExceptionWhenHasName() {
154+
155+
var parameter = new Parameter<>("someName", type, annotations, entity);
156+
assertThat(parameter.getRequiredName()).isEqualTo("someName");
157+
}
158+
159+
@Test // GH-3088
160+
void getRequiredNameThrowsExceptionWhenHasNoName() {
161+
162+
var parameter = new Parameter<>(null, type, annotations, entity);
163+
assertThatIllegalStateException().isThrownBy(() -> parameter.getRequiredName())
164+
.withMessage("No name associated with this parameter");
165+
}
166+
167+
@Test // GH-3088
168+
void hasNameReturnsTrueWhenHasName() {
169+
170+
var parameter = new Parameter<>("someName", type, annotations, entity);
171+
assertThat(parameter.hasName()).isTrue();
172+
}
173+
174+
@Test // GH-3088
175+
void hasNameReturnsFalseWhenHasNoName() {
176+
177+
var parameter = new Parameter<>(null, type, annotations, entity);
178+
assertThat(parameter.hasName()).isFalse();
179+
}
180+
152181
interface IFace {
153182

154183
record RecordMember(IFace iFace) {

0 commit comments

Comments
 (0)