Skip to content

Commit

Permalink
Allow abstract serializers/deserializer in @JsonComponent
Browse files Browse the repository at this point in the history
Previously JsonComponentModule tried to instantiate all
inner classes and failed with InstantiationException when
the class is abstract and extends JsonSerializer/JsonDeserializer.
With this change is now possible to have common logic inner abstract classes.

See spring-projectsgh-9443
  • Loading branch information
tsachev authored and snicoll committed Jun 15, 2017
1 parent acda4f9 commit 6ba7849
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package org.springframework.boot.jackson;

import java.lang.reflect.Modifier;
import java.util.Map;

import javax.annotation.PostConstruct;
Expand Down Expand Up @@ -78,8 +79,9 @@ private void addJsonBean(Object bean) {
addDeserializerWithDeducedType((JsonDeserializer<?>) bean);
}
for (Class<?> innerClass : bean.getClass().getDeclaredClasses()) {
if (JsonSerializer.class.isAssignableFrom(innerClass)
|| JsonDeserializer.class.isAssignableFrom(innerClass)) {
if (!Modifier.isAbstract(innerClass.getModifiers()) &&
(JsonSerializer.class.isAssignableFrom(innerClass)
|| JsonDeserializer.class.isAssignableFrom(innerClass))) {
try {
addJsonBean(innerClass.newInstance());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,15 @@ public void moduleShouldRegisterInnerClasses() throws Exception {
context.close();
}

@Test
public void moduleShouldAllowInnerAbstractClasses() throws Exception {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
JsonComponentModule.class, ComponentWithInnerAbstractClass.class);
JsonComponentModule module = context.getBean(JsonComponentModule.class);
assertSerialize(module);
context.close();
}

private void assertSerialize(Module module) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);
Expand All @@ -85,4 +94,15 @@ static class OnlyDeserializer extends NameAndAgeJsonComponent.Deserializer {

}

@JsonComponent
static class ComponentWithInnerAbstractClass {

private static abstract class AbstractSerializer extends NameAndAgeJsonComponent.Serializer {

}

static class ConcreteSerializer extends AbstractSerializer {

}
}
}

0 comments on commit 6ba7849

Please sign in to comment.