1 22 package org.jboss.xb.binding; 23 24 import org.jboss.logging.Logger; 25 26 import java.util.List ; 27 import java.lang.reflect.Constructor ; 28 29 33 public class Immutable 34 { 35 private static final Logger log = Logger.getLogger(Immutable.class); 36 37 public final Class cls; 38 39 final List names = new java.util.ArrayList (); 40 41 final List values = new java.util.ArrayList (); 42 43 public Immutable(Class cls) 44 { 45 this.cls = cls; 46 if(log.isTraceEnabled()) 47 { 48 log.trace("created immutable container for " + cls); 49 } 50 } 51 52 public void addChild(String localName, Object child) 53 { 54 if(!names.isEmpty() && names.get(names.size() - 1).equals(localName)) 55 { 56 throw new IllegalStateException ("Attempt to add duplicate element " + 57 localName + 58 ": prev value=" + 59 values.get(values.size() - 1) + 60 ", new value=" + 61 child 62 ); 63 } 64 names.add(localName); 65 values.add(child); 66 67 if(log.isTraceEnabled()) 68 { 69 log.trace("added child " + localName + " for " + cls + ": " + child); 70 } 71 } 72 73 public Object getChild(String localName) 74 { 75 return names.isEmpty() ? 76 null : 77 (names.get(names.size() - 1).equals(localName) ? values.get(values.size() - 1) : null); 78 } 79 80 public Object newInstance() 81 { 82 Constructor ctor = null; 83 Constructor [] ctors = cls.getConstructors(); 84 85 if(ctors == null || ctors.length == 0) 86 { 87 throw new JBossXBRuntimeException("The class has no declared constructors: " + cls); 88 } 89 90 for(int i = 0; i < ctors.length; ++i) 91 { 92 Class [] types = ctors[i].getParameterTypes(); 93 94 if(types == null || types.length == 0) 95 { 96 throw new IllegalStateException ("Found no-arg constructor for immutable " + cls); 97 } 98 99 if(types.length == values.size()) 100 { 101 ctor = ctors[i]; 102 103 int typeInd = 0; 104 while(typeInd < types.length) 105 { 106 if(!types[typeInd].isAssignableFrom(values.get(typeInd++).getClass())) 107 { 108 ctor = null; 109 break; 110 } 111 } 112 113 if(ctor != null) 114 { 115 break; 116 } 117 } 118 } 119 120 if(ctor == null) 121 { 122 throw new IllegalStateException ("No constructor in " + cls + " that would take arguments " + values); 123 } 124 125 try 126 { 127 return ctor.newInstance(values.toArray()); 128 } 129 catch(Exception e) 130 { 131 throw new IllegalStateException ("Failed to create immutable instance of " + 132 cls + 133 " using arguments: " 134 + values + ": " + e.getMessage() 135 ); 136 } 137 } 138 } 139 | Popular Tags |