1 52 53 package freemarker.ext.beans; 54 55 import java.lang.reflect.Array ; 56 57 import freemarker.ext.util.ModelFactory; 58 import freemarker.template.ObjectWrapper; 59 import freemarker.template.TemplateCollectionModel; 60 import freemarker.template.TemplateModel; 61 import freemarker.template.TemplateModelException; 62 import freemarker.template.TemplateModelIterator; 63 import freemarker.template.TemplateSequenceModel; 64 65 72 public class ArrayModel 73 extends 74 BeanModel 75 implements 76 TemplateCollectionModel, 77 TemplateSequenceModel 78 { 79 static final ModelFactory FACTORY = 80 new ModelFactory() 81 { 82 public TemplateModel create(Object object, ObjectWrapper wrapper) 83 { 84 return new ArrayModel(object, (BeansWrapper)wrapper); 85 } 86 }; 87 88 private int length; 90 91 100 public ArrayModel(Object array, BeansWrapper wrapper) 101 { 102 super(array, wrapper); 103 Class clazz = array.getClass(); 104 if(!clazz.isArray()) 105 throw new IllegalArgumentException ("Object is not an array, it is " + array.getClass().getName()); 106 length = Array.getLength(array); 107 } 108 109 110 public TemplateModelIterator iterator() 111 { 112 return new Iterator(); 113 } 114 115 public TemplateModel get(int index) 116 throws 117 TemplateModelException 118 { 119 try 120 { 121 return wrap(Array.get(object, index)); 122 } 123 catch(IndexOutOfBoundsException e) 124 { 125 throw new TemplateModelException("Index out of bounds: " + index); 126 } 127 } 128 129 private class Iterator 130 implements 131 TemplateSequenceModel, 132 TemplateModelIterator 133 { 134 private int position = 0; 135 136 public boolean hasNext() 137 { 138 return position < length; 139 } 140 141 public TemplateModel get(int index) 142 throws 143 TemplateModelException 144 { 145 return ArrayModel.this.get(index); 146 } 147 148 public TemplateModel next() 149 throws 150 TemplateModelException 151 { 152 return position < length ? get(position++) : null; 153 } 154 155 public int size() 156 { 157 return ArrayModel.this.size(); 158 } 159 } 160 161 public int size() 162 { 163 return length; 164 } 165 166 public boolean isEmpty() { 167 return length == 0; 168 } 169 } 170 | Popular Tags |