1 22 package org.jboss.xb.binding; 23 24 import java.lang.reflect.Array ; 25 import java.lang.reflect.Constructor ; 26 import java.util.ArrayList ; 27 import java.util.List ; 28 import javax.xml.namespace.QName ; 29 import org.jboss.xb.binding.sunday.unmarshalling.impl.runtime.RtUtil; 30 31 35 public interface GenericValueContainer 36 { 37 class FACTORY 38 { 39 public static GenericValueContainer array(final Class itemClass) 40 { 41 return array(null, null, itemClass); 42 } 43 44 public static GenericValueContainer array(final Class wrapperClass, 45 final String itemProperty, 46 final Class itemClass) 47 { 48 return new GenericValueContainer() 49 { 50 private final Class wrapperType = wrapperClass; 51 private final String itemProp = itemProperty; 52 private final Class itemType = itemClass; 53 private final List items = new ArrayList (); 54 55 public void addChild(QName name, Object value) 56 { 57 items.add(value); 58 } 59 60 public Object instantiate() 61 { 62 97 Object arr = Array.newInstance(itemType, items.size()); 98 for(int i = 0; i < items.size(); ++i) 99 { 100 try 101 { 102 Array.set(arr, i, items.get(i)); 103 } 104 catch(IllegalArgumentException e) 105 { 106 throw new JBossXBRuntimeException("Failed to set " + 107 items.get(i) + 108 " as an item of array " + arr 109 ); 110 } 111 } 112 113 Object result = arr; 114 if(wrapperType != null) 116 { 117 Constructor ctor = null; 118 try 119 { 120 try 121 { 122 ctor = wrapperType.getConstructor(null); 123 result = ctor.newInstance(null); 124 RtUtil.set(result, arr, itemProp, null, false, null); 125 } 126 catch(NoSuchMethodException e) 127 { 128 Constructor [] ctors = wrapperType.getConstructors(); 129 for(int i = 0; i < ctors.length; ++i) 130 { 131 Class [] types = ctors[i].getParameterTypes(); 132 if(types.length == 1 && types[0].isAssignableFrom(arr.getClass())) 133 { 134 ctor = ctors[i]; 135 break; 136 } 137 } 138 139 if(ctor == null) 140 { 141 throw new JBossXBRuntimeException("Failed to find an appropriate ctor in " + 142 wrapperType + 143 " to wrap " + arr 144 ); 145 } 146 147 result = ctor.newInstance(new Object []{arr}); 148 } 149 } 150 catch(JBossXBRuntimeException e) 151 { 152 throw e; 153 } 154 catch(Exception e) 155 { 156 throw new JBossXBRuntimeException( 157 "Failed to initialize array wrapper " + wrapperType + " for " + arr, e 158 ); 159 } 160 } 161 return result; 162 } 163 164 public Class getTargetClass() 165 { 166 return Array.newInstance(itemType, 0).getClass(); 169 } 170 171 public String toString() 172 { 173 return super.toString() + "array"; 174 } 175 }; 176 } 177 } 178 179 void addChild(QName name, Object value); 180 181 Object instantiate(); 182 183 Class getTargetClass(); 184 } 185 | Popular Tags |