Skip to content

Commit

Permalink
Prevent throwing NoSuchMethodException on direct getMethod calls
Browse files Browse the repository at this point in the history
Instead, get list of methods and filter it

Such exception are expensive in terms of generating stack, plus they
unnecessarily bloat JVM reports with tons of throws
  • Loading branch information
oskar-szwajkowski authored and martint committed Jul 23, 2024
1 parent 4b4b289 commit d818f66
Showing 1 changed file with 32 additions and 24 deletions.
56 changes: 32 additions & 24 deletions src/main/java/org/weakref/jmx/AnnotationUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,10 @@
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Stream;

import static java.util.Arrays.asList;

Expand Down Expand Up @@ -202,17 +204,15 @@ public static String getDescription(Method annotatedMethod)

public static String getDescription(Annotation... annotations)
{
String description = "";
for (Annotation annotation : annotations) {
try {
Method descriptionMethod = annotation.annotationType().getMethod("description");
description = descriptionMethod.invoke(annotation).toString();
}
catch (ReflectiveOperationException e) {
// ignore
}
}
return description;
return Stream.of(annotations)
.flatMap(annotation -> Arrays.stream(annotation.annotationType().getDeclaredMethods())
.filter(method -> "description".equals(method.getName()))
.findFirst()
.flatMap(descriptionMethod -> tryInvoke(descriptionMethod, annotation))
.stream()
)
.findFirst()
.orElse("");
}

public static String getName(Method annotatedMethod)
Expand All @@ -222,19 +222,16 @@ public static String getName(Method annotatedMethod)

public static String getName(Annotation... annotations)
{
String name = "";
for (Annotation annotation : annotations) {
if (annotation instanceof Managed) {
try {
Method nameMethod = annotation.annotationType().getMethod("name");
name = nameMethod.invoke(annotation).toString();
}
catch (ReflectiveOperationException e) {
// ignore
}
}
}
return name;
return Stream.of(annotations)
.filter(annotation -> annotation instanceof Managed)
.flatMap(managedAnnotation -> Arrays.stream(managedAnnotation.annotationType().getDeclaredMethods())
.filter(method -> "name".equals(method.getName()))
.findFirst()
.flatMap(nameMethod -> tryInvoke(nameMethod, managedAnnotation))
.stream()
)
.findFirst()
.orElse("");
}

/**
Expand Down Expand Up @@ -336,4 +333,15 @@ private static boolean isAnnotationPresent(Class<? extends Annotation> annotatio

return false;
}

private static Optional<String> tryInvoke(Method method, Annotation annotation)
{
try {
return Optional.of(method.invoke(annotation).toString());
}
catch (ReflectiveOperationException e) {
// ignore
return Optional.empty();
}
}
}

0 comments on commit d818f66

Please sign in to comment.