Skip to content

Commit 45effd9

Browse files
committed
Introduce ConversionService in junit-platform-commons
1 parent 85d2553 commit 45effd9

File tree

11 files changed

+446
-131
lines changed

11 files changed

+446
-131
lines changed

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

+12-16
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242
* {@link File}, {@link BigDecimal}, {@link BigInteger}, {@link Currency},
4343
* {@link Locale}, {@link URI}, {@link URL}, {@link UUID}, etc.
4444
*
45-
* <p>If the source and target types are identical the source object will not
45+
* <p>If the source and target types are identical, the source object will not
4646
* be modified.
4747
*
4848
* @since 5.0
@@ -106,30 +106,26 @@ public final Object convert(Object source, Class<?> targetType, ClassLoader clas
106106
return source;
107107
}
108108

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

122-
throw new ArgumentConversionException(
123-
String.format("No built-in converter for source type %s and target type %s",
124-
source.getClass().getTypeName(), targetType.getTypeName()));
115+
try {
116+
return delegateConversion(source, targetType, classLoader);
117+
}
118+
catch (ConversionException ex) {
119+
throw new ArgumentConversionException(ex.getMessage(), ex);
120+
}
125121
}
126122

127123
private LocaleConversionFormat getLocaleConversionFormat() {
128124
return context.getConfigurationParameter(DEFAULT_LOCALE_CONVERSION_FORMAT_PROPERTY_NAME, TRANSFORMER) //
129125
.orElse(LocaleConversionFormat.BCP_47);
130126
}
131127

132-
Object convert(String source, Class<?> targetType, ClassLoader classLoader) {
128+
Object delegateConversion(Object source, Class<?> targetType, ClassLoader classLoader) {
133129
return ConversionSupport.convert(source, targetType, classLoader);
134130
}
135131

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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+
17+
/**
18+
* {@code ConversionService} is an abstraction that allows an input object to
19+
* be converted to an instance of a different class.
20+
*
21+
* <p>Implementations are loaded via the {@link java.util.ServiceLoader} and must
22+
* follow the service provider requirements. They should not make any assumptions
23+
* regarding when they are instantiated or how often they are called. Since
24+
* instances may potentially be cached and called from different threads, they
25+
* should be thread-safe.
26+
*
27+
* <p>Extend {@link TypedConversionService} if your implementation always converts
28+
* from a given source type into a given target type and does not need access to
29+
* the {@link ClassLoader} to perform the conversion.
30+
*
31+
* @since 1.13
32+
* @see ConversionSupport
33+
* @see TypedConversionService
34+
*/
35+
@API(status = EXPERIMENTAL, since = "1.13")
36+
public interface ConversionService {
37+
38+
/**
39+
* Determine if the supplied source object can be converted into an instance
40+
* of the specified target type.
41+
*
42+
* @param source the source object to convert; may be {@code null} but only
43+
* if the target type is a reference type
44+
* @param targetType the target type the source should be converted into;
45+
* never {@code null}
46+
* @param classLoader the {@code ClassLoader} to use; never {@code null}
47+
* @return {@code true} if the supplied source can be converted
48+
*/
49+
boolean canConvert(Object source, Class<?> targetType, ClassLoader classLoader);
50+
51+
/**
52+
* Convert the supplied source object into an instance of the specified
53+
* target type.
54+
*
55+
* @param source the source object to convert; may be {@code null} but only
56+
* if the target type is a reference type
57+
* @param targetType the target type the source should be converted into;
58+
* never {@code null}
59+
* @param classLoader the {@code ClassLoader} to use; never {@code null}
60+
* @return the converted object; may be {@code null} but only if the target
61+
* type is a reference type
62+
* @throws ConversionException if an error occurs during the conversion
63+
*/
64+
Object convert(Object source, Class<?> targetType, ClassLoader classLoader) throws ConversionException;
65+
66+
}

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

+41-87
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,12 @@
1010

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

13-
import static java.util.Arrays.asList;
14-
import static java.util.Collections.unmodifiableList;
13+
import static org.apiguardian.api.API.Status.DEPRECATED;
1514
import static org.apiguardian.api.API.Status.EXPERIMENTAL;
16-
import static org.junit.platform.commons.util.ReflectionUtils.getWrapperType;
1715

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

2120
import org.apiguardian.api.API;
2221
import org.junit.platform.commons.util.ClassLoaderUtils;
@@ -30,17 +29,6 @@
3029
@API(status = EXPERIMENTAL, since = "1.11")
3130
public final class ConversionSupport {
3231

33-
private static final List<StringToObjectConverter> stringToObjectConverters = unmodifiableList(asList( //
34-
new StringToBooleanConverter(), //
35-
new StringToCharacterConverter(), //
36-
new StringToNumberConverter(), //
37-
new StringToClassConverter(), //
38-
new StringToEnumConverter(), //
39-
new StringToJavaTimeConverter(), //
40-
new StringToCommonJavaTypesConverter(), //
41-
new FallbackStringToObjectConverter() //
42-
));
43-
4432
private ConversionSupport() {
4533
/* no-op */
4634
}
@@ -49,43 +37,6 @@ private ConversionSupport() {
4937
* Convert the supplied source {@code String} into an instance of the specified
5038
* target type.
5139
*
52-
* <p>If the target type is {@code String}, the source {@code String} will not
53-
* be modified.
54-
*
55-
* <p>Some forms of conversion require a {@link ClassLoader}. If none is
56-
* provided, the {@linkplain ClassLoaderUtils#getDefaultClassLoader() default
57-
* ClassLoader} will be used.
58-
*
59-
* <p>This method is able to convert strings into primitive types and their
60-
* corresponding wrapper types ({@link Boolean}, {@link Character}, {@link Byte},
61-
* {@link Short}, {@link Integer}, {@link Long}, {@link Float}, and
62-
* {@link Double}), enum constants, date and time types from the
63-
* {@code java.time} package, as well as common Java types such as {@link Class},
64-
* {@link java.io.File}, {@link java.nio.file.Path}, {@link java.nio.charset.Charset},
65-
* {@link java.math.BigDecimal}, {@link java.math.BigInteger},
66-
* {@link java.util.Currency}, {@link java.util.Locale}, {@link java.util.UUID},
67-
* {@link java.net.URI}, and {@link java.net.URL}.
68-
*
69-
* <p>If the target type is not covered by any of the above, a convention-based
70-
* conversion strategy will be used to convert the source {@code String} into the
71-
* given target type by invoking a static factory method or factory constructor
72-
* defined in the target type. The search algorithm used in this strategy is
73-
* outlined below.
74-
*
75-
* <h4>Search Algorithm</h4>
76-
*
77-
* <ol>
78-
* <li>Search for a single, non-private static factory method in the target
79-
* type that converts from a String to the target type. Use the factory method
80-
* if present.</li>
81-
* <li>Search for a single, non-private constructor in the target type that
82-
* accepts a String. Use the constructor if present.</li>
83-
* </ol>
84-
*
85-
* <p>If multiple suitable factory methods are discovered they will be ignored.
86-
* If neither a single factory method nor a single constructor is found, the
87-
* convention-based conversion strategy will not apply.
88-
*
8940
* @param source the source {@code String} to convert; may be {@code null}
9041
* but only if the target type is a reference type
9142
* @param targetType the target type the source should be converted into;
@@ -97,48 +48,51 @@ private ConversionSupport() {
9748
* type is a reference type
9849
*
9950
* @since 1.11
51+
* @see DefaultConversionService
52+
* @deprecated Use {@link #convert(Object, Class, ClassLoader)} instead.
10053
*/
10154
@SuppressWarnings("unchecked")
55+
@Deprecated
56+
@API(status = DEPRECATED, since = "5.13")
10257
public static <T> T convert(String source, Class<T> targetType, 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-
}
58+
return (T) DefaultConversionService.INSTANCE.convert(source, targetType, getClassLoader(classLoader));
59+
}
11060

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

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) {
126-
// simply rethrow it
127-
throw (ConversionException) ex;
128-
}
129-
// else
130-
throw new ConversionException(
131-
String.format("Failed to convert String \"%s\" to type %s", source, targetType.getTypeName()), ex);
132-
}
133-
}
83+
ConversionService conversionService = Stream.concat( //
84+
StreamSupport.stream(serviceLoader.spliterator(), false), //
85+
Stream.of(DefaultConversionService.INSTANCE)) //
86+
.filter(candidate -> candidate.canConvert(source, targetType, classLoader)) //
87+
.findFirst() //
88+
.orElseThrow(() -> new ConversionException("No registered or built-in converter for source '" + source
89+
+ "' and target type " + targetType.getTypeName()));
13490

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

139-
private static Class<?> toWrapperType(Class<?> targetType) {
140-
Class<?> wrapperType = getWrapperType(targetType);
141-
return wrapperType != null ? wrapperType : targetType;
94+
private static ClassLoader getClassLoader(ClassLoader classLoader) {
95+
return classLoader != null ? classLoader : ClassLoaderUtils.getDefaultClassLoader();
14296
}
14397

14498
}

0 commit comments

Comments
 (0)