Merge pull request #486 from sormuras/master
ClassName.reflectionName() added.
diff --git a/src/main/java/com/squareup/javapoet/ClassName.java b/src/main/java/com/squareup/javapoet/ClassName.java
index 1ad3860..79a35d1 100644
--- a/src/main/java/com/squareup/javapoet/ClassName.java
+++ b/src/main/java/com/squareup/javapoet/ClassName.java
@@ -84,6 +84,24 @@
return new ClassName(names.subList(0, 2));
}
+ public String reflectionName() {
+ // trivial case: no nested names
+ if (names.size() == 2) {
+ String packageName = packageName();
+ if (packageName.isEmpty()) {
+ return names.get(1);
+ }
+ return packageName + "." + names.get(1);
+ }
+ // concat top level class name and nested names
+ StringBuilder builder = new StringBuilder();
+ builder.append(topLevelClassName());
+ for (String name : simpleNames().subList(1, simpleNames().size())) {
+ builder.append('$').append(name);
+ }
+ return builder.toString();
+ }
+
/**
* Returns a new {@link ClassName} instance for the specified {@code name} as nested inside this
* class.
diff --git a/src/test/java/com/squareup/javapoet/ClassNameTest.java b/src/test/java/com/squareup/javapoet/ClassNameTest.java
index 0fa82d7..303dfeb 100644
--- a/src/test/java/com/squareup/javapoet/ClassNameTest.java
+++ b/src/test/java/com/squareup/javapoet/ClassNameTest.java
@@ -135,4 +135,14 @@
} catch (IllegalArgumentException ignored) {
}
}
+
+ @Test
+ public void reflectionName() {
+ assertEquals("java.lang.Object", TypeName.OBJECT.reflectionName());
+ assertEquals("java.lang.Thread$State", ClassName.get(Thread.State.class).reflectionName());
+ assertEquals("java.util.Map$Entry", ClassName.get(Map.Entry.class).reflectionName());
+ assertEquals("Foo", ClassName.get("", "Foo").reflectionName());
+ assertEquals("Foo$Bar$Baz", ClassName.get("", "Foo", "Bar", "Baz").reflectionName());
+ assertEquals("a.b.c.Foo$Bar$Baz", ClassName.get("a.b.c", "Foo", "Bar", "Baz").reflectionName());
+ }
}