1 19 20 package org.apache.cayenne.access.types; 21 22 import java.lang.reflect.Method ; 23 import java.sql.CallableStatement ; 24 import java.sql.PreparedStatement ; 25 import java.sql.ResultSet ; 26 27 import org.apache.cayenne.dba.TypesMapping; 28 import org.apache.cayenne.map.DbAttribute; 29 import org.apache.cayenne.validation.ValidationResult; 30 31 42 public class EnumType implements ExtendedType { 43 44 protected Class enumClass; 45 protected Object [] values; 46 47 public EnumType(Class enumClass) { 48 if (enumClass == null) { 49 throw new IllegalArgumentException ("Null enum class"); 50 } 51 52 this.enumClass = enumClass; 53 54 try { 55 Method m = enumClass.getMethod("values"); 56 this.values = (Object []) m.invoke(null); 57 } 58 catch (Exception e) { 59 throw new IllegalArgumentException ("Class " 60 + enumClass.getName() 61 + " is not an Enum", e); 62 } 63 } 64 65 public String getClassName() { 66 return enumClass.getName(); 67 } 68 69 72 public boolean validateProperty( 73 Object source, 74 String property, 75 Object value, 76 DbAttribute dbAttribute, 77 ValidationResult validationResult) { 78 79 return AbstractType.validateNull( 80 source, 81 property, 82 value, 83 dbAttribute, 84 validationResult); 85 } 86 87 public void setJdbcObject( 88 PreparedStatement statement, 89 Object value, 90 int pos, 91 int type, 92 int precision) throws Exception { 93 94 if (value instanceof Enum ) { 95 96 Enum e = (Enum ) value; 97 98 if (TypesMapping.isNumeric(type)) { 99 statement.setInt(pos, e.ordinal()); 100 } 101 else { 102 statement.setString(pos, e.name()); 103 } 104 } 105 else { 106 statement.setNull(pos, type); 107 } 108 } 109 110 public Object materializeObject(ResultSet rs, int index, int type) throws Exception { 111 if (TypesMapping.isNumeric(type)) { 112 int i = rs.getInt(index); 113 return (rs.wasNull() || index < 0) ? null : values[i]; 114 } 115 else { 116 String string = rs.getString(index); 117 return string != null ? Enum.valueOf(enumClass, string) : null; 118 } 119 } 120 121 public Object materializeObject(CallableStatement rs, int index, int type) 122 throws Exception { 123 124 if (TypesMapping.isNumeric(type)) { 125 int i = rs.getInt(index); 126 return (rs.wasNull() || index < 0) ? null : values[i]; 127 } 128 else { 129 String string = rs.getString(index); 130 return string != null ? Enum.valueOf(enumClass, string) : null; 131 } 132 } 133 } 134 | Popular Tags |