在Velocity中访问数组的最佳方法是什么?

Ser*_*Amo 23 velocity

我有一个Java数组,如:

String[] arr = new String[] {"123","doc","projectReport.doc"};
Run Code Online (Sandbox Code Playgroud)

在我看来,访问的自然方式是:

 #set($att_id = $arr[0])
 #set($att_type = $arr[1])
 #set($att_name = $arr[2])
Run Code Online (Sandbox Code Playgroud)

但它没有用.我已经采用了这种解决方法.但是对于这么简单的任务来说,它的代码太多了.

#set($counter = 0)
#foreach($el in $arr)
    #if($counter==0)
        #set($att_id = $el)
    #elseif($counter==1)
        #set($att_type = $el)
    #elseif($counter==2)
         #set($att_name = $el)
    #end
    #set($counter = $counter + 1)
#end
Run Code Online (Sandbox Code Playgroud)

还有其他方法吗?

Nat*_*bna 25

您可以使用Velocity 1.6:对于名为$arrayone 的数组,可以使用$array.get($index).

在即将推出的Velocity 1.7中,人们可以做到$array[$index](以及$list[$index]$map[$key]).


Bri*_*ian 8

您可以将数组包装在一个List使用中Arrays.asList(T... a).新的List对象由原始数组支持,因此不会浪费地分配副本.即使对新列表所做的更改也会传播回阵列.

然后你可以使用$list.get(int index)Velocity中的对象.

如果您只需要从数组中获取一个或两个对象,您还可以使用Array.get(Object array, int index) 从数组中获取项目.