Skip to content

Commit

Permalink
Prefer Reflection/ModifierSupport over ReflectionUtils
Browse files Browse the repository at this point in the history
Instead of calling methods of the internal ReflectionUtils class,
internal code now uses equivalent methods of ReflectionSupport or
ModifierSupport, where possible. This is important since internal code
often serves as an example when looking to implement custom extensions.
  • Loading branch information
marcphilipp committed Aug 15, 2024
1 parent a5edcbf commit c24d9a6
Show file tree
Hide file tree
Showing 65 changed files with 185 additions and 167 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@
import java.util.function.Predicate;

import org.apiguardian.api.API;
import org.junit.platform.commons.support.ReflectionSupport;
import org.junit.platform.commons.support.SearchOption;
import org.junit.platform.commons.util.ClassUtils;
import org.junit.platform.commons.util.Preconditions;
import org.junit.platform.commons.util.ReflectionUtils;

/**
* {@code DisplayNameGenerator} defines the SPI for generating display names
Expand Down Expand Up @@ -379,7 +379,7 @@ static DisplayNameGenerator getDisplayNameGenerator(Class<?> generatorClass) {
if (generatorClass == IndicativeSentences.class) {
return IndicativeSentences.INSTANCE;
}
return (DisplayNameGenerator) ReflectionUtils.newInstance(generatorClass);
return (DisplayNameGenerator) ReflectionSupport.newInstance(generatorClass);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import org.junit.jupiter.api.extension.ExecutionCondition;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.platform.commons.JUnitException;
import org.junit.platform.commons.support.ReflectionSupport;
import org.junit.platform.commons.util.ClassLoaderUtils;
import org.junit.platform.commons.util.Preconditions;
import org.junit.platform.commons.util.ReflectionUtils;
Expand Down Expand Up @@ -67,13 +68,13 @@ Method getConditionMethod(String fullyQualifiedMethodName, ExtensionContext cont
String className = methodParts[0];
String methodName = methodParts[1];
ClassLoader classLoader = ClassLoaderUtils.getClassLoader(testClass);
Class<?> clazz = ReflectionUtils.tryToLoadClass(className, classLoader).getOrThrow(
Class<?> clazz = ReflectionSupport.tryToLoadClass(className, classLoader).getOrThrow(
cause -> new JUnitException(format("Could not load class [%s]", className), cause));
return findMethod(clazz, methodName);
}

private Method findMethod(Class<?> clazz, String methodName) {
return ReflectionUtils.findMethod(clazz, methodName) //
return ReflectionSupport.findMethod(clazz, methodName) //
.orElseGet(() -> ReflectionUtils.getRequiredMethod(clazz, methodName, ExtensionContext.class));
}

Expand All @@ -85,9 +86,9 @@ private boolean invokeConditionMethod(Method method, ExtensionContext context) {

Object testInstance = context.getTestInstance().orElse(null);
if (method.getParameterCount() == 0) {
return (boolean) ReflectionUtils.invokeMethod(method, testInstance);
return (boolean) ReflectionSupport.invokeMethod(method, testInstance);
}
return (boolean) ReflectionUtils.invokeMethod(method, testInstance, context);
return (boolean) ReflectionSupport.invokeMethod(method, testInstance, context);
}

private boolean acceptsExtensionContextOrNoArguments(Method method) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import java.util.EnumSet;
import org.apiguardian.api.API;
import org.junit.platform.commons.logging.Logger;
import org.junit.platform.commons.logging.LoggerFactory;
import org.junit.platform.commons.util.ReflectionUtils;
import org.junit.platform.commons.support.ReflectionSupport;
import org.junit.platform.commons.util.StringUtils;

/**
Expand Down Expand Up @@ -85,9 +85,9 @@ public enum JRE {
// that returns an instance of java.lang.Runtime.Version which has the
// following method: public int major()
Method versionMethod = Runtime.class.getMethod("version");
Object version = ReflectionUtils.invokeMethod(versionMethod, null);
Object version = ReflectionSupport.invokeMethod(versionMethod, null);
Method majorMethod = version.getClass().getMethod("major");
int major = (int) ReflectionUtils.invokeMethod(majorMethod, version);
int major = (int) ReflectionSupport.invokeMethod(majorMethod, version);
switch (major) {<%--
--%>@for(var jre : jres)<%--
--%>@if(jre.getVersion() != 8)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
import org.junit.platform.commons.function.Try;
import org.junit.platform.commons.logging.Logger;
import org.junit.platform.commons.logging.LoggerFactory;
import org.junit.platform.commons.util.ReflectionUtils;
import org.junit.platform.commons.support.ReflectionSupport;
import org.junit.platform.engine.ConfigurationParameters;

/**
Expand Down Expand Up @@ -49,9 +49,9 @@ Supplier<Optional<T>> supply(ConfigurationParameters configurationParameters, St
}

private Supplier<Optional<T>> newInstanceSupplier(String className, String key) {
Try<Class<?>> clazz = ReflectionUtils.tryToLoadClass(className);
Try<Class<?>> clazz = ReflectionSupport.tryToLoadClass(className);
// @formatter:off
return () -> clazz.andThenTry(ReflectionUtils::newInstance)
return () -> clazz.andThenTry(ReflectionSupport::newInstance)
.andThenTry(this.clazz::cast)
.ifSuccess(generator -> logSuccessMessage(className, key))
.ifFailure(cause -> logFailureMessage(className, key, cause))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@
import org.junit.jupiter.engine.config.JupiterConfiguration;
import org.junit.platform.commons.logging.Logger;
import org.junit.platform.commons.logging.LoggerFactory;
import org.junit.platform.commons.support.ReflectionSupport;
import org.junit.platform.commons.support.SearchOption;
import org.junit.platform.commons.util.Preconditions;
import org.junit.platform.commons.util.ReflectionUtils;
import org.junit.platform.commons.util.StringUtils;

/**
Expand Down Expand Up @@ -137,7 +137,7 @@ private static Optional<DisplayNameGenerator> findDisplayNameGenerator(Class<?>
if (displayNameGeneratorClass == IndicativeSentences.class) {
return indicativeSentencesGenerator;
}
return ReflectionUtils.newInstance(displayNameGeneratorClass);
return ReflectionSupport.newInstance(displayNameGeneratorClass);
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import org.junit.jupiter.engine.extension.ExtensionRegistrar;
import org.junit.jupiter.engine.extension.MutableExtensionRegistry;
import org.junit.platform.commons.PreconditionViolationException;
import org.junit.platform.commons.support.ModifierSupport;
import org.junit.platform.commons.util.Preconditions;
import org.junit.platform.commons.util.ReflectionUtils;

Expand Down Expand Up @@ -89,7 +90,7 @@ static MutableExtensionRegistry populateNewExtensionRegistryFromExtendWithAnnota
* @since 5.11
*/
static void registerExtensionsFromStaticFields(ExtensionRegistrar registrar, Class<?> clazz) {
streamExtensionRegisteringFields(clazz, ReflectionUtils::isStatic) //
streamExtensionRegisteringFields(clazz, ModifierSupport::isStatic) //
.forEach(field -> {
List<Class<? extends Extension>> extensionTypes = streamDeclarativeExtensionTypes(field).collect(
toList());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
import org.junit.jupiter.api.BeforeEach;
import org.junit.platform.commons.JUnitException;
import org.junit.platform.commons.support.HierarchyTraversalMode;
import org.junit.platform.commons.util.ReflectionUtils;
import org.junit.platform.commons.support.ModifierSupport;

/**
* Collection of utilities for working with test lifecycle methods.
Expand Down Expand Up @@ -81,15 +81,15 @@ private static List<Method> findMethodsAndCheckVoidReturnType(Class<?> testClass
}

private static void assertStatic(Class<? extends Annotation> annotationType, Method method) {
if (ReflectionUtils.isNotStatic(method)) {
if (ModifierSupport.isNotStatic(method)) {
throw new JUnitException(String.format(
"@%s method '%s' must be static unless the test class is annotated with @TestInstance(Lifecycle.PER_CLASS).",
annotationType.getSimpleName(), method.toGenericString()));
}
}

private static void assertNonStatic(Class<? extends Annotation> annotationType, Method method) {
if (ReflectionUtils.isStatic(method)) {
if (ModifierSupport.isStatic(method)) {
throw new JUnitException(String.format("@%s method '%s' must not be static.",
annotationType.getSimpleName(), method.toGenericString()));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
import org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor;
import org.junit.jupiter.engine.descriptor.JupiterEngineDescriptor;
import org.junit.platform.commons.support.AnnotationSupport;
import org.junit.platform.commons.util.ReflectionUtils;
import org.junit.platform.commons.support.ReflectionSupport;
import org.junit.platform.engine.TestDescriptor;

/**
Expand Down Expand Up @@ -59,7 +59,7 @@ protected DescriptorWrapperOrderer getDescriptorWrapperOrderer(
AnnotatedElement annotatedElement = descriptorWrapper.getAnnotatedElement();
return AnnotationSupport.findAnnotation(annotatedElement, TestClassOrder.class)//
.map(TestClassOrder::value)//
.<ClassOrderer> map(ReflectionUtils::newInstance)//
.<ClassOrderer> map(ReflectionSupport::newInstance)//
.map(this::createDescriptorWrapperOrderer)//
.orElse(inheritedDescriptorWrapperOrderer);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@
import static java.util.function.Predicate.isEqual;
import static java.util.stream.Collectors.toCollection;
import static org.junit.jupiter.engine.discovery.predicates.IsTestClassWithTests.isTestOrTestFactoryOrTestTemplateMethod;
import static org.junit.platform.commons.support.HierarchyTraversalMode.TOP_DOWN;
import static org.junit.platform.commons.support.ReflectionSupport.findMethods;
import static org.junit.platform.commons.support.ReflectionSupport.streamNestedClasses;
import static org.junit.platform.commons.util.FunctionUtils.where;
import static org.junit.platform.commons.util.ReflectionUtils.findMethods;
import static org.junit.platform.engine.discovery.DiscoverySelectors.selectUniqueId;
import static org.junit.platform.engine.support.discovery.SelectorResolver.Resolution.unresolved;

Expand All @@ -35,7 +36,7 @@
import org.junit.jupiter.engine.descriptor.NestedClassTestDescriptor;
import org.junit.jupiter.engine.discovery.predicates.IsNestedTestClass;
import org.junit.jupiter.engine.discovery.predicates.IsTestClassWithTests;
import org.junit.platform.commons.util.ReflectionUtils;
import org.junit.platform.commons.support.ReflectionSupport;
import org.junit.platform.engine.DiscoverySelector;
import org.junit.platform.engine.TestDescriptor;
import org.junit.platform.engine.UniqueId;
Expand Down Expand Up @@ -93,7 +94,7 @@ public Resolution resolve(UniqueIdSelector selector, Context context) {
UniqueId.Segment lastSegment = uniqueId.getLastSegment();
if (ClassTestDescriptor.SEGMENT_TYPE.equals(lastSegment.getType())) {
String className = lastSegment.getValue();
return ReflectionUtils.tryToLoadClass(className).toOptional().filter(isTestClassWithTests).map(
return ReflectionSupport.tryToLoadClass(className).toOptional().filter(isTestClassWithTests).map(
testClass -> toResolution(
context.addToParent(parent -> Optional.of(newClassTestDescriptor(parent, testClass))))).orElse(
unresolved());
Expand All @@ -103,7 +104,7 @@ public Resolution resolve(UniqueIdSelector selector, Context context) {
return toResolution(context.addToParent(() -> selectUniqueId(uniqueId.removeLastSegment()), parent -> {
if (parent instanceof ClassBasedTestDescriptor) {
Class<?> parentTestClass = ((ClassBasedTestDescriptor) parent).getTestClass();
return ReflectionUtils.findNestedClasses(parentTestClass,
return ReflectionSupport.findNestedClasses(parentTestClass,
isNestedTestClass.and(
where(Class::getSimpleName, isEqual(simpleClassName)))).stream().findFirst().flatMap(
testClass -> Optional.of(newNestedClassTestDescriptor(parent, testClass)));
Expand Down Expand Up @@ -133,7 +134,7 @@ private Resolution toResolution(Optional<? extends ClassBasedTestDescriptor> tes
testClasses.add(testClass);
// @formatter:off
return Resolution.match(Match.exact(it, () -> {
Stream<DiscoverySelector> methods = findMethods(testClass, isTestOrTestFactoryOrTestTemplateMethod).stream()
Stream<DiscoverySelector> methods = findMethods(testClass, isTestOrTestFactoryOrTestTemplateMethod, TOP_DOWN).stream()
.map(method -> selectMethod(testClasses, method));
Stream<NestedClassSelector> nestedClasses = streamNestedClasses(testClass, isNestedTestClass)
.map(nestedClass -> DiscoverySelectors.selectNestedClass(testClasses, nestedClass));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.junit.platform.commons.support.ReflectionSupport;
import org.junit.platform.commons.util.Preconditions;
import org.junit.platform.commons.util.ReflectionUtils;

/**
* @since 5.0
Expand All @@ -34,7 +34,7 @@ Optional<Method> findMethod(String methodSpecPart, Class<?> clazz) {

String methodName = matcher.group(1);
String parameterTypeNames = matcher.group(2);
return ReflectionUtils.findMethod(clazz, methodName, parameterTypeNames);
return ReflectionSupport.findMethod(clazz, methodName, parameterTypeNames);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
import org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor;
import org.junit.jupiter.engine.descriptor.JupiterTestDescriptor;
import org.junit.jupiter.engine.descriptor.MethodBasedTestDescriptor;
import org.junit.platform.commons.util.ReflectionUtils;
import org.junit.platform.commons.support.ReflectionSupport;
import org.junit.platform.engine.TestDescriptor;

/**
Expand Down Expand Up @@ -50,7 +50,7 @@ public void visit(TestDescriptor testDescriptor) {
private void orderContainedMethods(ClassBasedTestDescriptor classBasedTestDescriptor, Class<?> testClass) {
findAnnotation(testClass, TestMethodOrder.class)//
.map(TestMethodOrder::value)//
.<MethodOrderer> map(ReflectionUtils::newInstance)//
.<MethodOrderer> map(ReflectionSupport::newInstance)//
.map(Optional::of)//
.orElseGet(configuration::getDefaultTestMethodOrderer)//
.ifPresent(methodOrderer -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
package org.junit.jupiter.engine.discovery.predicates;

import static org.apiguardian.api.API.Status.INTERNAL;
import static org.junit.platform.commons.support.ModifierSupport.isPrivate;
import static org.junit.platform.commons.util.ReflectionUtils.isInnerClass;
import static org.junit.platform.commons.util.ReflectionUtils.isPrivate;

import java.util.function.Predicate;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@
package org.junit.jupiter.engine.discovery.predicates;

import static org.apiguardian.api.API.Status.INTERNAL;
import static org.junit.platform.commons.util.ReflectionUtils.isAbstract;
import static org.junit.platform.commons.support.ModifierSupport.isAbstract;
import static org.junit.platform.commons.support.ModifierSupport.isPrivate;
import static org.junit.platform.commons.util.ReflectionUtils.isInnerClass;
import static org.junit.platform.commons.util.ReflectionUtils.isPrivate;

import java.util.function.Predicate;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import java.util.function.Predicate;

import org.apiguardian.api.API;
import org.junit.platform.commons.support.ReflectionSupport;
import org.junit.platform.commons.util.ReflectionUtils;

/**
Expand Down Expand Up @@ -51,7 +52,7 @@ private boolean hasTestOrTestFactoryOrTestTemplateMethods(Class<?> candidate) {
}

private boolean hasNestedTests(Class<?> candidate) {
return !ReflectionUtils.findNestedClasses(candidate, isNestedTestClass).isEmpty();
return !ReflectionSupport.findNestedClasses(candidate, isNestedTestClass).isEmpty();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@
package org.junit.jupiter.engine.discovery.predicates;

import static org.junit.platform.commons.support.AnnotationSupport.isAnnotated;
import static org.junit.platform.commons.util.ReflectionUtils.isAbstract;
import static org.junit.platform.commons.util.ReflectionUtils.isPrivate;
import static org.junit.platform.commons.util.ReflectionUtils.isStatic;
import static org.junit.platform.commons.support.ModifierSupport.isAbstract;
import static org.junit.platform.commons.support.ModifierSupport.isPrivate;
import static org.junit.platform.commons.support.ModifierSupport.isStatic;
import static org.junit.platform.commons.util.ReflectionUtils.returnsPrimitiveVoid;

import java.lang.annotation.Annotation;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

import org.junit.jupiter.api.extension.InvocationInterceptor.Invocation;
import org.junit.jupiter.api.extension.ReflectiveInvocationContext;
import org.junit.platform.commons.util.ReflectionUtils;
import org.junit.platform.commons.support.ReflectionSupport;

class MethodInvocation<T> implements Invocation<T>, ReflectiveInvocationContext<Method> {

Expand Down Expand Up @@ -57,7 +57,7 @@ public List<Object> getArguments() {
@Override
@SuppressWarnings("unchecked")
public T proceed() {
return (T) ReflectionUtils.invokeMethod(this.method, this.target.orElse(null), this.arguments);
return (T) ReflectionSupport.invokeMethod(this.method, this.target.orElse(null), this.arguments);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
import org.junit.platform.commons.logging.Logger;
import org.junit.platform.commons.logging.LoggerFactory;
import org.junit.platform.commons.support.AnnotationSupport;
import org.junit.platform.commons.support.ModifierSupport;
import org.junit.platform.commons.support.ReflectionSupport;
import org.junit.platform.commons.util.Preconditions;
import org.junit.platform.commons.util.ReflectionUtils;
import org.junit.platform.commons.util.StringUtils;
Expand Down Expand Up @@ -58,7 +60,7 @@ public void afterAll(ExtensionContext context) {
}

private static void closeFields(Class<?> testClass, Object testInstance, ThrowableCollector throwableCollector) {
Predicate<Field> predicate = (testInstance == null ? ReflectionUtils::isStatic : ReflectionUtils::isNotStatic);
Predicate<Field> predicate = (testInstance == null ? ModifierSupport::isStatic : ModifierSupport::isNotStatic);
AnnotationSupport.findAnnotatedFields(testClass, AutoClose.class, predicate, BOTTOM_UP).forEach(
field -> throwableCollector.execute(() -> closeField(field, testInstance)));
}
Expand All @@ -71,7 +73,7 @@ private static void closeField(Field field, Object testInstance) throws Exceptio
checkCondition(!fieldType.isPrimitive(), "@AutoClose is not supported on primitive field %s.", field);
checkCondition(!fieldType.isArray(), "@AutoClose is not supported on array field %s.", field);

Object fieldValue = ReflectionUtils.tryToReadFieldValue(field, testInstance).get();
Object fieldValue = ReflectionSupport.tryToReadFieldValue(field, testInstance).get();
if (fieldValue == null) {
logger.warn(() -> String.format("Cannot @AutoClose field %s because it is null.", getQualifiedName(field)));
}
Expand All @@ -88,13 +90,13 @@ private static void invokeCloseMethod(Field field, Object target, String methodN
}

Class<?> targetType = target.getClass();
Method closeMethod = ReflectionUtils.findMethod(targetType, methodName).orElseThrow(
Method closeMethod = ReflectionSupport.findMethod(targetType, methodName).orElseThrow(
() -> new ExtensionConfigurationException(
String.format("Cannot @AutoClose field %s because %s does not define method %s().",
getQualifiedName(field), targetType.getName(), methodName)));

closeMethod = ReflectionUtils.getInterfaceMethodIfPossible(closeMethod, targetType);
ReflectionUtils.invokeMethod(closeMethod, target);
ReflectionSupport.invokeMethod(closeMethod, target);
}

private static void checkCondition(boolean condition, String messageFormat, Field field) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@
import org.junit.jupiter.engine.config.JupiterConfiguration;
import org.junit.platform.commons.logging.Logger;
import org.junit.platform.commons.logging.LoggerFactory;
import org.junit.platform.commons.support.ReflectionSupport;
import org.junit.platform.commons.util.ClassLoaderUtils;
import org.junit.platform.commons.util.Preconditions;
import org.junit.platform.commons.util.ReflectionUtils;

/**
* Default, mutable implementation of {@link ExtensionRegistry}.
Expand Down Expand Up @@ -148,7 +148,7 @@ public <E extends Extension> Stream<E> stream(Class<E> extensionType) {
@Override
public void registerExtension(Class<? extends Extension> extensionType) {
if (!isAlreadyRegistered(extensionType)) {
registerLocalExtension(ReflectionUtils.newInstance(extensionType));
registerLocalExtension(ReflectionSupport.newInstance(extensionType));
}
}

Expand Down
Loading

0 comments on commit c24d9a6

Please sign in to comment.