1 3 package jodd.typeconverter; 4 5 import java.sql.Blob ; 6 import java.sql.SQLException ; 7 8 11 public class ByteArrayConverter implements TypeConverter { 12 13 public static byte[] valueOf(Object value) { 14 if (value == null) { 15 return null; 16 } 17 Class type = value.getClass(); 18 if (type.isArray() == false) { 19 if (value instanceof Number ) { 20 return new byte[] {((Number ) value).byteValue()}; 21 } 22 if (value instanceof Blob ) { 23 Blob blob = (Blob ) value; 24 try { 25 long length = blob.length(); 26 if (length > Integer.MAX_VALUE) { 27 throw new TypeConversionException("Blob is too big."); 28 } 29 return blob.getBytes(1, (int) length); 30 } catch (SQLException sex) { 31 throw new TypeConversionException(sex); 32 } 33 } 34 try { 35 return new byte[] {Byte.parseByte(value.toString())}; 36 } catch (NumberFormatException nfex) { 37 throw new TypeConversionException(nfex); 38 } 39 } 40 41 if (type == byte[].class) { 42 return (byte[]) value; 43 } 44 if (type == int[].class) { 45 int[] values = (int[]) value; 46 byte[] results = new byte[values.length]; 47 for (int i = 0; i < values.length; i++) { 48 results[i] = (byte) values[i]; 49 } 50 return results; 51 } 52 if (type == long[].class) { 53 long[] values = (long[]) value; 54 byte[] results = new byte[values.length]; 55 for (int i = 0; i < values.length; i++) { 56 results[i] = (byte) values[i]; 57 } 58 return results; 59 } 60 if (type == double[].class) { 61 double[] values = (double[]) value; 62 byte[] results = new byte[values.length]; 63 for (int i = 0; i < values.length; i++) { 64 results[i] = (byte) values[i]; 65 } 66 return results; 67 } 68 if (type == float[].class) { 69 float[] values = (float[]) value; 70 byte[] results = new byte[values.length]; 71 for (int i = 0; i < values.length; i++) { 72 results[i] = (byte) values[i]; 73 } 74 return results; 75 } 76 if (type == boolean[].class) { 77 boolean[] values = (boolean[]) value; 78 byte[] results = new byte[values.length]; 79 for (int i = 0; i < values.length; i++) { 80 results[i] = (byte) (values[i] == true ? 1 : 0); 81 } 82 return results; 83 } 84 if (type == short[].class) { 85 short[] values = (short[]) value; 86 byte[] results = new byte[values.length]; 87 for (int i = 0; i < values.length; i++) { 88 results[i] = (byte) values[i]; 89 } 90 return results; 91 } 92 93 94 Object [] values = (Object []) value; 95 byte[] results = new byte[values.length]; 96 try { 97 for (int i = 0; i < values.length; i++) { 98 if (values[i] instanceof Number ) { 99 results[i] = ((Number ) values[i]).byteValue(); 100 } else { 101 results[i] = Byte.parseByte(values[i].toString()); 102 } 103 } 104 } catch (NumberFormatException nfex) { 105 throw new TypeConversionException(nfex); 106 } 107 return results; 108 } 109 110 public Object convert(Object value) { 111 return valueOf(value); 112 } 113 } 114 | Popular Tags |