1 17 18 package org.apache.avalon.util.criteria; 19 20 import java.lang.reflect.Constructor ; 21 import java.io.Serializable ; 22 23 30 public class Parameter implements Serializable 31 { 32 36 42 public static String [] getKeys( Parameter[] params ) 43 { 44 String [] keys = new String [ params.length ]; 45 for( int i=0; i<params.length; i++ ) 46 { 47 keys[i] = params[i].getKey(); 48 } 49 return keys; 50 } 51 52 56 private final String m_key; 57 private final Class m_type; 58 private final boolean m_required; 59 private final Object m_default; 60 61 65 70 public Parameter( 71 final String key, final Class type ) 72 { 73 m_key = key; 74 m_type = type; 75 m_required = true; 76 m_default = null; 77 } 78 79 85 public Parameter( 86 final String key, final Class type, Object value ) 87 { 88 m_key = key; 89 m_type = type; 90 m_required = false; 91 m_default = value; 92 } 93 94 98 102 public String getKey() 103 { 104 return m_key; 105 } 106 107 111 public Class getParameterClass() 112 { 113 return m_type; 114 } 115 116 120 public boolean isRequired() 121 { 122 return m_required; 123 } 124 125 129 public boolean isOptional() 130 { 131 return !isRequired(); 132 } 133 134 138 public Object getDefault() 139 { 140 return m_default; 141 } 142 143 149 public Object resolve( Object value ) throws CriteriaException 150 { 151 return resolve( m_type, value ); 152 } 153 154 161 protected Object resolve( Class type, Object value ) throws CriteriaException 162 { 163 if( value == null ) 164 return null; 165 if( type == null ) 166 throw new NullPointerException ( "type" ); 167 if( type.isInstance( value ) ) 168 { 169 return value; 170 } 171 else 172 { 173 Constructor constructor = null; 174 try 175 { 176 constructor = 177 type.getConstructor( 178 new Class []{ value.getClass() } ); 179 } 180 catch( NoSuchMethodException nsme ) 181 { 182 final String error = 183 "Value of class: [" 184 + value.getClass().getName() 185 + "] supplied for key [" 186 + getKey() 187 + "] is not an instance of type: [" 188 + type.getName() 189 + "]."; 190 throw new CriteriaException( error ); 191 } 192 193 try 194 { 195 return constructor.newInstance( 196 new Object []{ value } ); 197 } 198 catch( Throwable e ) 199 { 200 final String error = 201 "Value of class: [" 202 + value.getClass().getName() 203 + "] supplied for key [" 204 + getKey() 205 + "] is not an instance of or was not resolvable to the type: [" 206 + type.getName() 207 + "]."; 208 throw new CriteriaException( error, e ); 209 } 210 } 211 } 212 } 213 | Popular Tags |