1 16 17 package org.apache.velocity.tools.generic; 18 19 import java.lang.reflect.Array ; 20 import java.lang.reflect.Method ; 21 import java.util.ArrayList ; 22 import java.util.List ; 23 24 57 public class ExtendedListTool extends ListTool { 58 59 62 public ExtendedListTool() { 63 } 64 65 88 public List toList(Object array) { 89 if (this.isList(array)) { 90 return (List ) array; 91 } 92 if (!this.isArray(array)) { 93 return null; 94 } 95 96 int length = Array.getLength(array); 98 List asList = new ArrayList (length); 99 for (int index = 0; index < length; ++index) { 100 asList.add(Array.get(array, index)); 101 } 102 return asList; 103 } 104 105 125 public Object toArray(Object list) { 126 if (this.isArray(list)) { 127 return list; 128 } 129 if (!this.isList(list)) { 130 return null; 131 } 132 133 List asList = (List ) list; 134 return asList.toArray(new Object [asList.size()]); 135 } 136 137 150 public Integer length(Object array) { 151 if (this.isList(array)) { 152 return this.size(array); 153 } 154 if (!this.isArray(array)) { 155 return null; 156 } 157 158 return new Integer (Array.getLength(array)); 160 } 161 162 173 public Object clone(Object list) { 174 if (this.isArray(list)) { 175 Class type = list.getClass().getComponentType(); 176 int length = Array.getLength(list); 177 Object clone = Array.newInstance(type, length); 178 System.arraycopy(list, 0, clone, 0, length); 179 return clone; 180 } 181 if (!this.isList(list)) { 182 return null; 183 } 184 185 Class clazz = list.getClass(); 187 try { 188 Method cloneMethod = clazz.getMethod("clone", new Class [0]); 189 return cloneMethod.invoke(list, null); 190 } 191 catch (Exception ignoreAndTryTheNextStep) { 192 } 193 194 try { 196 List clone = (List ) clazz.newInstance(); 197 clone.addAll(((List ) list)); 198 return clone; 199 } 200 catch (Exception ignoreAndTryTheNextStep) { 201 } 202 203 return new ArrayList (((List ) list)); 205 } 206 207 } | Popular Tags |