Skip to content

Commit 3e51d80

Browse files
committed
Added method for checking if a class has a method with a certain name
1 parent 882af78 commit 3e51d80

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

src/main/java/org/bbottema/javareflection/ClassUtils.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,15 @@ public static List<Method> collectMethodsByName(final Class<?> type, Class<?> bo
257257
return collectMethodsMappingToName(type, boundaryMarker, methodModifiers).get(methodName);
258258
}
259259

260+
/**
261+
* @return Whether {@link #collectMethodsMappingToName(Class, Class, EnumSet)} contains a method with the given name.
262+
*/
263+
@SuppressWarnings("WeakerAccess")
264+
public static boolean hasMethodByName(final Class<?> type, Class<?> boundaryMarker, EnumSet<MethodModifier> methodModifiers, final String methodName) {
265+
LinkedHashMap<String, List<Method>> methodsByName = collectMethodsMappingToName(type, boundaryMarker, methodModifiers);
266+
return methodsByName.containsKey(methodName) && !methodsByName.get(methodName).isEmpty();
267+
}
268+
260269
/**
261270
* @return The first result of {@link #collectMethodsByName(Class, Class, EnumSet, String)}.
262271
* <strong>Note: </strong> methods are ordered in groups (see {@link #collectMethods(Class, Class, EnumSet)})).

src/test/java/org/bbottema/javareflection/ClassUtilsTest.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,13 @@ public void testFindFirstMethodsByName() {
135135
assertThat(ClassUtils.findFirstMethodByName(C.class, Object.class, MATCH_ANY, "protectedMethod"))
136136
.extracting("name").containsExactly("protectedMethod");
137137
}
138+
139+
@Test
140+
public void testHasMethodByName() {
141+
assertThat(ClassUtils.hasMethodByName(C.class, C.class, MATCH_ANY, "foo")).isTrue();
142+
assertThat(ClassUtils.hasMethodByName(C.class, Object.class, MATCH_ANY, "protectedMethod")).isTrue();
143+
assertThat(ClassUtils.hasMethodByName(C.class, Object.class, MATCH_ANY, "lalala")).isFalse();
144+
}
138145

139146
@Test
140147
public void testCollectMethodsMappingToName() {

0 commit comments

Comments
 (0)