Skip to content

Commit d5bb2ae

Browse files
committed
Introduce Converter in junit-platform-commons
1 parent e9d71d6 commit d5bb2ae

File tree

24 files changed

+650
-203
lines changed

24 files changed

+650
-203
lines changed

junit-jupiter-params/src/main/java/org/junit/jupiter/params/aggregator/DefaultArgumentsAccessor.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import org.jspecify.annotations.Nullable;
2222
import org.junit.jupiter.api.extension.ExtensionContext;
2323
import org.junit.jupiter.params.converter.DefaultArgumentConverter;
24+
import org.junit.platform.commons.support.conversion.TypeDescriptor;
2425
import org.junit.platform.commons.util.ClassUtils;
2526
import org.junit.platform.commons.util.Preconditions;
2627

@@ -47,7 +48,7 @@ public static DefaultArgumentsAccessor create(ExtensionContext context, int invo
4748

4849
BiFunction<@Nullable Object, Class<?>, @Nullable Object> converter = (source,
4950
targetType) -> new DefaultArgumentConverter(context) //
50-
.convert(source, targetType, classLoader);
51+
.convert(source, TypeDescriptor.forClass(targetType), classLoader);
5152
return new DefaultArgumentsAccessor(converter, invocationIndex, arguments);
5253
}
5354

junit-jupiter-params/src/main/java/org/junit/jupiter/params/converter/DefaultArgumentConverter.java

Lines changed: 18 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
import org.junit.jupiter.params.support.FieldContext;
3131
import org.junit.platform.commons.support.conversion.ConversionException;
3232
import org.junit.platform.commons.support.conversion.ConversionSupport;
33+
import org.junit.platform.commons.support.conversion.TypeDescriptor;
3334
import org.junit.platform.commons.util.ReflectionUtils;
3435

3536
/**
@@ -43,7 +44,7 @@
4344
* {@link File}, {@link BigDecimal}, {@link BigInteger}, {@link Currency},
4445
* {@link Locale}, {@link URI}, {@link URL}, {@link UUID}, etc.
4546
*
46-
* <p>If the source and target types are identical the source object will not
47+
* <p>If the source and target types are identical, the source object will not
4748
* be modified.
4849
*
4950
* @since 5.0
@@ -82,48 +83,42 @@ public DefaultArgumentConverter(ExtensionContext context) {
8283

8384
@Override
8485
public final @Nullable Object convert(@Nullable Object source, ParameterContext context) {
85-
Class<?> targetType = context.getParameter().getType();
8686
ClassLoader classLoader = getClassLoader(context.getDeclaringExecutable().getDeclaringClass());
87-
return convert(source, targetType, classLoader);
87+
return convert(source, TypeDescriptor.forParameter(context.getParameter()), classLoader);
8888
}
8989

9090
@Override
9191
public final @Nullable Object convert(@Nullable Object source, FieldContext context)
9292
throws ArgumentConversionException {
93-
94-
Class<?> targetType = context.getField().getType();
9593
ClassLoader classLoader = getClassLoader(context.getField().getDeclaringClass());
96-
return convert(source, targetType, classLoader);
94+
return convert(source, TypeDescriptor.forField(context.getField()), classLoader);
9795
}
9896

99-
public final @Nullable Object convert(@Nullable Object source, Class<?> targetType, ClassLoader classLoader) {
97+
public final @Nullable Object convert(@Nullable Object source, TypeDescriptor targetType, ClassLoader classLoader) {
10098
if (source == null) {
10199
if (targetType.isPrimitive()) {
102100
throw new ArgumentConversionException(
103-
"Cannot convert null to primitive value of type " + targetType.getTypeName());
101+
"Cannot convert null to primitive value of type " + targetType.getType().getTypeName());
104102
}
105103
return null;
106104
}
107105

108-
if (ReflectionUtils.isAssignableTo(source, targetType)) {
106+
if (ReflectionUtils.isAssignableTo(source, targetType.getType())) {
109107
return source;
110108
}
111109

112-
if (source instanceof String string) {
113-
if (targetType == Locale.class && getLocaleConversionFormat() == LocaleConversionFormat.BCP_47) {
114-
return Locale.forLanguageTag(string);
115-
}
116-
117-
try {
118-
return convert(string, targetType, classLoader);
119-
}
120-
catch (ConversionException ex) {
121-
throw new ArgumentConversionException(ex.getMessage(), ex);
122-
}
110+
if (source instanceof String //
111+
&& targetType.getType() == Locale.class //
112+
&& getLocaleConversionFormat() == LocaleConversionFormat.BCP_47) {
113+
return Locale.forLanguageTag((String) source);
123114
}
124115

125-
throw new ArgumentConversionException("No built-in converter for source type %s and target type %s".formatted(
126-
source.getClass().getTypeName(), targetType.getTypeName()));
116+
try {
117+
return delegateConversion(source, targetType, classLoader);
118+
}
119+
catch (ConversionException ex) {
120+
throw new ArgumentConversionException(ex.getMessage(), ex);
121+
}
127122
}
128123

129124
private LocaleConversionFormat getLocaleConversionFormat() {
@@ -132,7 +127,7 @@ private LocaleConversionFormat getLocaleConversionFormat() {
132127
}
133128

134129
@Nullable
135-
Object convert(@Nullable String source, Class<?> targetType, ClassLoader classLoader) {
130+
Object delegateConversion(@Nullable Object source, TypeDescriptor targetType, ClassLoader classLoader) {
136131
return ConversionSupport.convert(source, targetType, classLoader);
137132
}
138133

junit-platform-commons/src/main/java/module-info.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,5 +58,6 @@
5858
org.junit.platform.suite.engine,
5959
org.junit.platform.testkit,
6060
org.junit.vintage.engine;
61+
uses org.junit.platform.commons.support.conversion.Converter;
6162
uses org.junit.platform.commons.support.scanning.ClasspathScanner;
6263
}

junit-platform-commons/src/main/java/org/junit/platform/commons/support/conversion/ConversionSupport.java

Lines changed: 44 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,12 @@
1010

1111
package org.junit.platform.commons.support.conversion;
1212

13+
import static org.apiguardian.api.API.Status.DEPRECATED;
1314
import static org.apiguardian.api.API.Status.EXPERIMENTAL;
14-
import static org.junit.platform.commons.util.ReflectionUtils.getWrapperType;
1515

16-
import java.util.List;
17-
import java.util.Optional;
16+
import java.util.ServiceLoader;
17+
import java.util.stream.Stream;
18+
import java.util.stream.StreamSupport;
1819

1920
import org.apiguardian.api.API;
2021
import org.jspecify.annotations.Nullable;
@@ -29,17 +30,6 @@
2930
@API(status = EXPERIMENTAL, since = "1.11")
3031
public final class ConversionSupport {
3132

32-
private static final List<StringToObjectConverter> stringToObjectConverters = List.of( //
33-
new StringToBooleanConverter(), //
34-
new StringToCharacterConverter(), //
35-
new StringToNumberConverter(), //
36-
new StringToClassConverter(), //
37-
new StringToEnumConverter(), //
38-
new StringToJavaTimeConverter(), //
39-
new StringToCommonJavaTypesConverter(), //
40-
new FallbackStringToObjectConverter() //
41-
);
42-
4333
private ConversionSupport() {
4434
/* no-op */
4535
}
@@ -48,43 +38,6 @@ private ConversionSupport() {
4838
* Convert the supplied source {@code String} into an instance of the specified
4939
* target type.
5040
*
51-
* <p>If the target type is {@code String}, the source {@code String} will not
52-
* be modified.
53-
*
54-
* <p>Some forms of conversion require a {@link ClassLoader}. If none is
55-
* provided, the {@linkplain ClassLoaderUtils#getDefaultClassLoader() default
56-
* ClassLoader} will be used.
57-
*
58-
* <p>This method is able to convert strings into primitive types and their
59-
* corresponding wrapper types ({@link Boolean}, {@link Character}, {@link Byte},
60-
* {@link Short}, {@link Integer}, {@link Long}, {@link Float}, and
61-
* {@link Double}), enum constants, date and time types from the
62-
* {@code java.time} package, as well as common Java types such as {@link Class},
63-
* {@link java.io.File}, {@link java.nio.file.Path}, {@link java.nio.charset.Charset},
64-
* {@link java.math.BigDecimal}, {@link java.math.BigInteger},
65-
* {@link java.util.Currency}, {@link java.util.Locale}, {@link java.util.UUID},
66-
* {@link java.net.URI}, and {@link java.net.URL}.
67-
*
68-
* <p>If the target type is not covered by any of the above, a convention-based
69-
* conversion strategy will be used to convert the source {@code String} into the
70-
* given target type by invoking a static factory method or factory constructor
71-
* defined in the target type. The search algorithm used in this strategy is
72-
* outlined below.
73-
*
74-
* <h4>Search Algorithm</h4>
75-
*
76-
* <ol>
77-
* <li>Search for a single, non-private static factory method in the target
78-
* type that converts from a String to the target type. Use the factory method
79-
* if present.</li>
80-
* <li>Search for a single, non-private constructor in the target type that
81-
* accepts a String. Use the constructor if present.</li>
82-
* </ol>
83-
*
84-
* <p>If multiple suitable factory methods are discovered they will be ignored.
85-
* If neither a single factory method nor a single constructor is found, the
86-
* convention-based conversion strategy will not apply.
87-
*
8841
* @param source the source {@code String} to convert; may be {@code null}
8942
* but only if the target type is a reference type
9043
* @param targetType the target type the source should be converted into;
@@ -96,49 +49,54 @@ private ConversionSupport() {
9649
* type is a reference type
9750
*
9851
* @since 1.11
52+
* @see DefaultConverter
53+
* @deprecated Use {@link #convert(Object, TypeDescriptor, ClassLoader)} instead.
9954
*/
100-
@SuppressWarnings("unchecked")
55+
@Deprecated
56+
@API(status = DEPRECATED, since = "6.0")
10157
public static <T> @Nullable T convert(@Nullable String source, Class<T> targetType,
10258
@Nullable ClassLoader classLoader) {
103-
if (source == null) {
104-
if (targetType.isPrimitive()) {
105-
throw new ConversionException(
106-
"Cannot convert null to primitive value of type " + targetType.getTypeName());
107-
}
108-
return null;
109-
}
59+
return convert(source, TypeDescriptor.forClass(targetType), getClassLoader(classLoader));
60+
}
11061

111-
if (String.class.equals(targetType)) {
112-
return (T) source;
113-
}
62+
/**
63+
* Convert the supplied source object into an instance of the specified
64+
* target type.
65+
*
66+
* @param source the source object to convert; may be {@code null}
67+
* but only if the target type is a reference type
68+
* @param targetType the target type the source should be converted into;
69+
* never {@code null}
70+
* @param classLoader the {@code ClassLoader} to use; may be {@code null} to
71+
* use the default {@code ClassLoader}
72+
* @param <T> the type of the target
73+
* @return the converted object; may be {@code null} but only if the target
74+
* type is a reference type
75+
*
76+
* @since 6.0
77+
*/
78+
@API(status = EXPERIMENTAL, since = "6.0")
79+
@SuppressWarnings("unchecked")
80+
public static <T> @Nullable T convert(@Nullable Object source, TypeDescriptor targetType,
81+
@Nullable ClassLoader classLoader) {
82+
TypeDescriptor sourceType = TypeDescriptor.forInstance(source);
83+
ClassLoader classLoaderToUse = getClassLoader(classLoader);
84+
ServiceLoader<Converter> serviceLoader = ServiceLoader.load(Converter.class, classLoaderToUse);
11485

115-
Class<?> targetTypeToUse = toWrapperType(targetType);
116-
Optional<StringToObjectConverter> converter = stringToObjectConverters.stream().filter(
117-
candidate -> candidate.canConvertTo(targetTypeToUse)).findFirst();
118-
if (converter.isPresent()) {
119-
try {
120-
ClassLoader classLoaderToUse = classLoader != null ? classLoader
121-
: ClassLoaderUtils.getDefaultClassLoader();
122-
return (T) converter.get().convert(source, targetTypeToUse, classLoaderToUse);
123-
}
124-
catch (Exception ex) {
125-
if (ex instanceof ConversionException conversionException) {
126-
// simply rethrow it
127-
throw conversionException;
128-
}
129-
// else
130-
throw new ConversionException(
131-
"Failed to convert String \"%s\" to type %s".formatted(source, targetType.getTypeName()), ex);
132-
}
133-
}
86+
Converter converter = Stream.concat( //
87+
StreamSupport.stream(serviceLoader.spliterator(), false), //
88+
Stream.of(DefaultConverter.INSTANCE)) //
89+
.filter(candidate -> candidate.canConvert(source, sourceType, targetType)) //
90+
.findFirst() //
91+
.orElseThrow(() -> new ConversionException(
92+
"No registered or built-in converter for source '%s' and target type %s".formatted( //
93+
source, targetType.getTypeName())));
13494

135-
throw new ConversionException(
136-
"No built-in converter for source type java.lang.String and target type " + targetType.getTypeName());
95+
return (T) converter.convert(source, sourceType, targetType, classLoaderToUse);
13796
}
13897

139-
private static Class<?> toWrapperType(Class<?> targetType) {
140-
Class<?> wrapperType = getWrapperType(targetType);
141-
return wrapperType != null ? wrapperType : targetType;
98+
private static ClassLoader getClassLoader(@Nullable ClassLoader classLoader) {
99+
return classLoader != null ? classLoader : ClassLoaderUtils.getDefaultClassLoader();
142100
}
143101

144102
}
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/*
2+
* Copyright 2015-2025 the original author or authors.
3+
*
4+
* All rights reserved. This program and the accompanying materials are
5+
* made available under the terms of the Eclipse Public License v2.0 which
6+
* accompanies this distribution and is available at
7+
*
8+
* https://www.eclipse.org/legal/epl-v20.html
9+
*/
10+
11+
package org.junit.platform.commons.support.conversion;
12+
13+
import static org.apiguardian.api.API.Status.EXPERIMENTAL;
14+
15+
import org.apiguardian.api.API;
16+
import org.jspecify.annotations.Nullable;
17+
18+
/**
19+
* {@code Converter} is an abstraction that allows an input object to
20+
* be converted to an instance of a different class.
21+
*
22+
* <p>Implementations are loaded via the {@link java.util.ServiceLoader} and must
23+
* follow the service provider requirements. They should not make any assumptions
24+
* regarding when they are instantiated or how often they are called. Since
25+
* instances may potentially be cached and called from different threads, they
26+
* should be thread-safe.
27+
*
28+
* <p>Extend {@link TypedConverter} if your implementation always converts
29+
* from a given source type into a given target type and does not need access to
30+
* the {@link ClassLoader} to perform the conversion.
31+
*
32+
* @since 6.0
33+
* @see ConversionSupport
34+
* @see TypedConverter
35+
*/
36+
@API(status = EXPERIMENTAL, since = "6.0")
37+
public interface Converter {
38+
39+
/**
40+
* Determine if the supplied source object can be converted into an instance
41+
* of the specified target type.
42+
*
43+
* @param source the source object to convert; may be {@code null} but only
44+
* if the target type is a reference type
45+
* @param sourceType the descriptor of the source type; never {@code null}
46+
* @param targetType the descriptor of the type the source should be converted into;
47+
* never {@code null}
48+
* @return {@code true} if the supplied source can be converted
49+
*/
50+
boolean canConvert(@Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType);
51+
52+
/**
53+
* Convert the supplied source object into an instance of the specified
54+
* target type.
55+
* <p>This method will only be invoked if {@link #canConvert(Object, TypeDescriptor, TypeDescriptor)}
56+
* returned {@code true} for the same target type.
57+
*
58+
* @param source the source object to convert; may be {@code null} but only
59+
* if the target type is a reference type
60+
* @param sourceType the descriptor of the source type; never {@code null}
61+
* @param targetType the descriptor of the type the source should be converted into;
62+
* never {@code null}
63+
* @param classLoader the {@code ClassLoader} to use; never {@code null}
64+
* @return the converted object; may be {@code null} but only if the target
65+
* type is a reference type
66+
* @throws ConversionException if an error occurs during the conversion
67+
*/
68+
@Nullable
69+
Object convert(@Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType,
70+
ClassLoader classLoader) throws ConversionException;
71+
72+
}

0 commit comments

Comments
 (0)