Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for automatic detection of subtypes (like @JsonSubTypes) from Java 17 sealed types #5025

Merged
merged 9 commits into from
Mar 18, 2025
Original file line number Diff line number Diff line change
Expand Up @@ -651,13 +651,27 @@ public TypeResolverBuilder<?> findPropertyContentTypeResolver(MapperConfig<?> co
public List<NamedType> findSubtypes(MapperConfig<?> config, Annotated a)
{
JsonSubTypes t = _findAnnotation(a, JsonSubTypes.class);
if (t == null) return null;
if(t != null) {
return findSubtypesByJsonSubTypesAnnotation(config, a, t);
}

if(a.getAnnotated() instanceof Class<?> clazz && clazz.isSealed()
&& clazz.getPermittedSubclasses().length > 0) {
return findSubtypesByPermittedSubclasses(config, a, clazz);
}

return null;
}

// @since 3.0
private List<NamedType> findSubtypesByJsonSubTypesAnnotation(MapperConfig<?> config, Annotated a, JsonSubTypes t)
{
JsonSubTypes.Type[] types = t.value();

// 02-Aug-2022, tatu: As per [databind#3500], may need to check uniqueness
// of names
if (t.failOnRepeatedNames()) {
return findSubtypesCheckRepeatedNames(a.getName(), types);
return findSubtypesByJsonSubTypesAnnotationCheckRepeatedNames(a.getName(), types);
} else {
ArrayList<NamedType> result = new ArrayList<NamedType>(types.length);
for (JsonSubTypes.Type type : types) {
Expand All @@ -671,8 +685,8 @@ public List<NamedType> findSubtypes(MapperConfig<?> config, Annotated a)
}
}

// @since 2.14
private List<NamedType> findSubtypesCheckRepeatedNames(String annotatedTypeName, JsonSubTypes.Type[] types)
// @since 3.0
private List<NamedType> findSubtypesByJsonSubTypesAnnotationCheckRepeatedNames(String annotatedTypeName, JsonSubTypes.Type[] types)
{
ArrayList<NamedType> result = new ArrayList<NamedType>(types.length);
Set<String> seenNames = new HashSet<>();
Expand All @@ -698,6 +712,16 @@ private List<NamedType> findSubtypesCheckRepeatedNames(String annotatedTypeName,

return result;
}

// @since 3.0
private List<NamedType> findSubtypesByPermittedSubclasses(MapperConfig<?> config, Annotated a, Class<?> clazz)
{
List<NamedType> result = new ArrayList<>(clazz.getPermittedSubclasses().length);
for (Class<?> subtype : clazz.getPermittedSubclasses()) {
result.add(new NamedType(subtype));
}
return result;
}

@Override
public String findTypeName(MapperConfig<?> config, AnnotatedClass ac)
Expand Down
Loading