From dba2f05b134b1eab0e64b7b816e76145f8a35c5f Mon Sep 17 00:00:00 2001 From: Eric Cochran Date: Wed, 10 Jan 2018 18:56:37 -0800 Subject: [PATCH] Improve error message for local classes. (#423) --- .../com/squareup/moshi/ClassJsonAdapter.java | 15 ++++++++------- .../squareup/moshi/ClassJsonAdapterTest.java | 17 ++++++++++++++++- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/moshi/src/main/java/com/squareup/moshi/ClassJsonAdapter.java b/moshi/src/main/java/com/squareup/moshi/ClassJsonAdapter.java index 087a428..76c929d 100644 --- a/moshi/src/main/java/com/squareup/moshi/ClassJsonAdapter.java +++ b/moshi/src/main/java/com/squareup/moshi/ClassJsonAdapter.java @@ -57,14 +57,15 @@ final class ClassJsonAdapter extends JsonAdapter { } 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.getSimpleName().isEmpty()) { - throw new IllegalArgumentException( - "Cannot serialize anonymous class " + rawType.getName()); - } else { - throw new IllegalArgumentException( - "Cannot serialize non-static nested class " + rawType.getName()); - } + throw new IllegalArgumentException( + "Cannot serialize non-static nested class " + rawType.getName()); } if (Modifier.isAbstract(rawType.getModifiers())) { throw new IllegalArgumentException("Cannot serialize abstract class " + rawType.getName()); diff --git a/moshi/src/test/java/com/squareup/moshi/ClassJsonAdapterTest.java b/moshi/src/test/java/com/squareup/moshi/ClassJsonAdapterTest.java index fa58aaf..ff28f28 100644 --- a/moshi/src/test/java/com/squareup/moshi/ClassJsonAdapterTest.java +++ b/moshi/src/test/java/com/squareup/moshi/ClassJsonAdapterTest.java @@ -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 { - assertThat(ClassJsonAdapter.FACTORY.create(Runnable.class, NO_ANNOTATIONS, moshi)).isNull(); + assertThat(ClassJsonAdapter.FACTORY.create(Interface.class, NO_ANNOTATIONS, moshi)).isNull(); } static abstract class Abstract {