Support index access on primitive arrays

This commit is contained in:
Masaki Mori
2015-09-14 13:45:08 +09:00
parent 2efcfb69ed
commit 4b713862c8
2 changed files with 33 additions and 1 deletions
@@ -43,8 +43,15 @@ public class DefaultCollector extends BasicCollector
Mustache.VariableFetcher fetcher = super.createFetcher(ctx, name); Mustache.VariableFetcher fetcher = super.createFetcher(ctx, name);
if (fetcher != null) return fetcher; if (fetcher != null) return fetcher;
// first check for a getter which provides the value
Class<?> cclass = ctx.getClass(); Class<?> cclass = ctx.getClass();
// try generic 'indexing' fetcher for primitive arrays
char c = name.charAt(0);
if (c >= '0' && c <= '9') {
if (cclass.isArray()) return GENERIC_ARRAY_FETCHER;
}
// first check for a getter which provides the value
final Method m = getMethod(cclass, name); final Method m = getMethod(cclass, name);
if (m != null) { if (m != null) {
return new Mustache.VariableFetcher() { return new Mustache.VariableFetcher() {
@@ -162,4 +169,16 @@ public class DefaultCollector extends BasicCollector
} }
return null; return null;
} }
protected static final Mustache.VariableFetcher GENERIC_ARRAY_FETCHER = new Mustache.VariableFetcher() {
public Object get (Object ctx, String name) throws Exception {
try {
return Array.get(ctx, Integer.parseInt(name));
} catch (NumberFormatException nfe) {
return Template.NO_FETCHER_FOUND;
} catch (IndexOutOfBoundsException e) {
return Template.NO_FETCHER_FOUND;
}
}
};
} }
@@ -89,6 +89,19 @@ public class MustacheTest
}); });
} }
@Test public void testPrimitiveArrayIndexVariable () {
test("1", "{{foo.0}}", new Object() {
int[] getFoo () { return new int[] { 1, 2, 3, 4 }; }
});
}
@Test public void testPrimitiveArrayIndexOutOfBoundsVariable () {
Mustache.Compiler comp = Mustache.compiler().defaultValue("?");
test(comp, "?", "{{foo.4}}", new Object() {
int[] getFoo () { return new int[] { 1, 2, 3, 4 }; }
});
}
@Test public void testCallSiteReuse () { @Test public void testCallSiteReuse () {
Template tmpl = Mustache.compiler().compile("{{foo}}"); Template tmpl = Mustache.compiler().compile("{{foo}}");
Object ctx = new Object() { Object ctx = new Object() {