简体   繁体   中英

Weird NullPointerException in StringTemplate map operation

This is my StringTemplate template for generating import statements, which does map operation on the anonymous template {i | import <i>;<\\n>} {i | import <i>;<\\n>} for every value in imports .

importdecl(imports) ::= "<if(imports)> <imports: {i | import <i>;<\\n>}> <endif>"

This throws java.lang.NullPointerException at org.stringtemplate.v4.misc.ErrorManager.runTimeError(ErrorManager.java:133) .

And the weird part is, when I change i to something else, this works perfectly and I'm sure that there is no difference in the input in both the cases. Like this doesn't throw error,

importdecl(imports) ::= "<if(imports)> <imports: {r | import <r>;<\\n>}> <endif>"

Is i reserved or something in StringTemplate or am I missing something?

<i> is used to access the 1 based index in the array.

For example,

ST st = stGroup.getInstanceOf("importdecl");
int[] data = {4, 5};
st.add("imports", data);
System.out.println(st.render());

with a template of

importdecl(imports) ::= <<
  <if(imports)><imports: {k | import <i><k>;<\n>}><endif>
>>

Prints:

import 14;
import 25;

I'd suggest using a different variable name :)

More info here and here

Yes i is reserved.List of reserved keywords:

i, i0

The iteration number indexed from one and from zero, respectively, when referenced within a template being applied to an attribute or attributes.

  • default
  • first
  • group
  • if
  • implements
  • interface
  • last
  • length
  • optional
  • rest
  • strip
  • super
  • trunc
  • else
  • endif
  • elseif

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM