Improve error message for local classes. (#423)

This commit is contained in:
Eric Cochran
2018-01-10 18:56:37 -08:00
committed by Jesse Wilson
parent 5d12c22f44
commit dba2f05b13
2 changed files with 24 additions and 8 deletions

View File

@@ -57,15 +57,16 @@ final class ClassJsonAdapter<T> extends JsonAdapter<T> {
} }
if (!annotations.isEmpty()) return null; if (!annotations.isEmpty()) return null;
if (rawType.isAnonymousClass()) {
throw new IllegalArgumentException("Cannot serialize anonymous class " + rawType.getName());
}
if (rawType.isLocalClass()) {
throw new IllegalArgumentException("Cannot serialize local class " + rawType.getName());
}
if (rawType.getEnclosingClass() != null && !Modifier.isStatic(rawType.getModifiers())) { if (rawType.getEnclosingClass() != null && !Modifier.isStatic(rawType.getModifiers())) {
if (rawType.getSimpleName().isEmpty()) {
throw new IllegalArgumentException(
"Cannot serialize anonymous class " + rawType.getName());
} else {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Cannot serialize non-static nested class " + rawType.getName()); "Cannot serialize non-static nested class " + rawType.getName());
} }
}
if (Modifier.isAbstract(rawType.getModifiers())) { if (Modifier.isAbstract(rawType.getModifiers())) {
throw new IllegalArgumentException("Cannot serialize abstract class " + rawType.getName()); throw new IllegalArgumentException("Cannot serialize abstract class " + rawType.getName());
} }

View File

@@ -341,8 +341,23 @@ public final class ClassJsonAdapterTest {
} }
} }
@Test public void localClassNotSupported() throws Exception {
class Local {
}
try {
ClassJsonAdapter.FACTORY.create(Local.class, NO_ANNOTATIONS, moshi);
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected).hasMessage("Cannot serialize local class "
+ "com.squareup.moshi.ClassJsonAdapterTest$1Local");
}
}
interface Interface {
}
@Test public void interfaceNotSupported() throws Exception { @Test public void interfaceNotSupported() throws Exception {
assertThat(ClassJsonAdapter.FACTORY.create(Runnable.class, NO_ANNOTATIONS, moshi)).isNull(); assertThat(ClassJsonAdapter.FACTORY.create(Interface.class, NO_ANNOTATIONS, moshi)).isNull();
} }
static abstract class Abstract { static abstract class Abstract {