1 16 package org.apache.myfaces.convert; 17 18 19 25 public final class ConverterUtils 26 { 27 29 private ConverterUtils() {} 30 31 32 public static int convertToInt(Object value) 33 { 34 if (value instanceof Number ) 35 { 36 return ((Number )value).intValue(); 37 } 38 else if (value instanceof String ) 39 { 40 try 41 { 42 return Integer.parseInt((String )value); 43 } 44 catch (NumberFormatException e) 45 { 46 throw new IllegalArgumentException ("Cannot convert " + value.toString() + " to int"); 47 } 48 } 49 else 50 { 51 throw new IllegalArgumentException ("Cannot convert " + value.toString() + " to int"); 52 } 53 } 54 55 public static boolean convertToBoolean(Object value) 56 { 57 if (value instanceof Boolean ) 58 { 59 return ((Boolean )value).booleanValue(); 60 } 61 else if (value instanceof String ) 62 { 63 try 64 { 65 return new Boolean ((String )value).booleanValue(); 66 } 67 catch (Exception e) 68 { 69 throw new IllegalArgumentException ("Cannot convert " + value.toString() + " to boolean"); 70 } 71 } 72 else 73 { 74 throw new IllegalArgumentException ("Cannot convert " + value.toString() + " to int"); 75 } 76 } 77 78 public static long convertToLong(Object value) 79 { 80 if (value instanceof Number ) 81 { 82 return ((Number )value).longValue(); 83 } 84 else if (value instanceof String ) 85 { 86 try 87 { 88 return Long.parseLong((String )value); 89 } 90 catch (NumberFormatException e) 91 { 92 throw new IllegalArgumentException ("Cannot convert " + value.toString() + " to long"); 93 } 94 } 95 else 96 { 97 throw new IllegalArgumentException ("Cannot convert " + value.toString() + " to long"); 98 } 99 } 100 101 public static double convertToDouble(Object value) 102 { 103 if (value instanceof Number ) 104 { 105 return ((Number )value).doubleValue(); 106 } 107 else if (value instanceof String ) 108 { 109 try 110 { 111 return Double.parseDouble((String )value); 112 } 113 catch (NumberFormatException e) 114 { 115 throw new IllegalArgumentException ("Cannot convert " + value.toString() + " to double"); 116 } 117 } 118 else 119 { 120 throw new IllegalArgumentException ("Cannot convert " + value.toString() + " to double"); 121 } 122 } 123 124 125 } 126 | Popular Tags |