Merge pull request #145 from mpoindexter/master-add-class-simplename

Implement Class.getSimpleName
This commit is contained in:
Alexey Andreev 2015-07-21 18:36:04 +03:00
commit 0e4f14958a
2 changed files with 39 additions and 0 deletions

View File

@ -17,6 +17,7 @@ package org.teavm.classlib.java.lang;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.teavm.classlib.impl.DeclaringClassMetadataGenerator; import org.teavm.classlib.impl.DeclaringClassMetadataGenerator;
import org.teavm.classlib.java.lang.annotation.TAnnotation; import org.teavm.classlib.java.lang.annotation.TAnnotation;
import org.teavm.classlib.java.lang.reflect.TAnnotatedElement; import org.teavm.classlib.java.lang.reflect.TAnnotatedElement;
@ -32,6 +33,7 @@ import org.teavm.platform.metadata.ClassScopedMetadataProvider;
*/ */
public class TClass<T> extends TObject implements TAnnotatedElement { public class TClass<T> extends TObject implements TAnnotatedElement {
TString name; TString name;
TString simpleName;
private TClass<?> componentType; private TClass<?> componentType;
private boolean componentTypeDirty = true; private boolean componentTypeDirty = true;
private PlatformClass platformClass; private PlatformClass platformClass;
@ -73,6 +75,30 @@ public class TClass<T> extends TObject implements TAnnotatedElement {
return name; return name;
} }
public TString getSimpleName() {
if (simpleName == null) {
if (isArray()) {
simpleName = getComponentType().getSimpleName().concat(TString.wrap("[]"));
return simpleName;
}
String name = platformClass.getMetadata().getName();
int lastDollar = name.lastIndexOf('$');
if (lastDollar != -1) {
name = name.substring(lastDollar + 1);
if (name.charAt(0) >= '0' && name.charAt(0) <= '9') {
name = "";
}
} else {
int lastDot = name.lastIndexOf('.');
if (lastDot != -1) {
name = name.substring(lastDot + 1);
}
}
simpleName = TString.wrap(name);
}
return simpleName;
}
public boolean isPrimitive() { public boolean isPrimitive() {
return platformClass.getMetadata().isPrimitive(); return platformClass.getMetadata().isPrimitive();
} }

View File

@ -38,6 +38,16 @@ public class ClassTest {
assertEquals("[I", int[].class.getName()); assertEquals("[I", int[].class.getName());
} }
@Test
public void classSimpleNameEvaluated() {
assertEquals("Object", Object.class.getSimpleName());
assertEquals("Object[]", Object[].class.getSimpleName());
assertEquals("int", int.class.getSimpleName());
assertEquals("int[]", int[].class.getSimpleName());
assertEquals("InnerClass", InnerClass.class.getSimpleName());
assertEquals("", new Object(){}.getClass().getSimpleName());
}
@Test @Test
public void objectClassNameEvaluated() { public void objectClassNameEvaluated() {
assertEquals("java.lang.Object", new Object().getClass().getName()); assertEquals("java.lang.Object", new Object().getClass().getName());
@ -205,4 +215,7 @@ public class ClassTest {
Class<?> n(); Class<?> n();
} }
static class InnerClass {
}
} }