1 56 57 package org.jdom.contrib.beans; 58 59 import java.lang.reflect.*; 60 import java.util.*; 61 62 67 68 public class StringConverter { 69 70 public static interface Factory { 71 public Object instantiate(String string); 72 } 73 74 public static class DateFactory implements StringConverter.Factory 75 { 76 public Object instantiate(String string) { 77 return DateUtils.parseDate(string); 78 } 79 } 80 81 protected Map factories = new HashMap(); 82 83 public StringConverter() { 84 try { 85 factories.put( Class.forName("java.util.Date"), 86 new DateFactory() ); 87 } 88 catch (ClassNotFoundException e) {} 89 } 90 91 public void setFactory(Class type, Factory factory) { 92 factories.put(type, factory); 93 } 94 95 protected static Class [] argString = new Class [] { String .class }; 96 97 public Object parse(String string, Class type) 98 { 99 if (type == String .class) { 101 return string; 102 } 103 104 Factory factory = (Factory)factories.get(type); 106 if (factory != null) { 107 return factory.instantiate(string); 108 } 109 110 if (type == short.class) type = Short .class; 112 if (type == int.class) type = Integer .class; 113 if (type == long.class) type = Long .class; 114 if (type == boolean.class) type = Boolean .class; 115 if (type == char.class) type = Character .class; 116 if (type == byte.class) type = Byte .class; 117 118 try { 120 Constructor c = type.getConstructor(argString); 121 if (c != null) { 122 return c.newInstance( new Object [] { string } ); 123 } 124 } 125 catch (NoSuchMethodException e) { 126 } 128 catch (Exception e) { 129 System.err.println("Couldn't instantiate " + type + "(" + string + ")"); 130 e.printStackTrace(); 131 } 132 133 return null; 134 } 135 } 136 | Popular Tags |