1 2 12 package com.versant.core.jdo.externalizer; 13 14 import com.versant.core.common.BindingSupportImpl; 15 import com.versant.core.common.Utils; 16 17 import javax.jdo.PersistenceManager; 18 import java.lang.reflect.Constructor ; 19 import java.lang.reflect.Method ; 20 import java.io.Externalizable ; 21 import java.io.ObjectInput ; 22 import java.io.IOException ; 23 import java.io.ObjectOutput ; 24 25 34 public class TypeAsStringExternalizer 35 implements Externalizer, Externalizable { 36 37 public static final String SHORT_NAME = "STRING"; 38 39 private Class type; 40 private transient Constructor constructor; 41 private transient Method toExternalString; 42 43 public TypeAsStringExternalizer(Class type) { 44 this.type = type; 45 init(); 46 } 47 48 public TypeAsStringExternalizer() { 49 } 50 51 private void init() { 52 try { 53 constructor = type.getConstructor(new Class []{String .class}); 54 } catch (NoSuchMethodException e) { 55 throw BindingSupportImpl.getInstance().runtime(type + 56 " does not have a " + 57 "constructor that accepts a String", e); 58 } 59 try { 60 toExternalString = type.getMethod("toExternalString", null); 61 if (toExternalString.getReturnType() != String .class) { 62 throw BindingSupportImpl.getInstance().runtime(type + 63 ".toExternalString() does not " + 64 "return String"); 65 } 66 } catch (NoSuchMethodException e) { 67 } 69 } 70 71 public Object toExternalForm(PersistenceManager pm, Object o) { 72 if (o == null) return null; 73 try { 74 return toExternalString == null 75 ? o.toString() 76 : (String )toExternalString.invoke(o, null); 77 } catch (Throwable x) { 78 throw BindingSupportImpl.getInstance().runtime("Unable to convert instance of " + 79 type.getName() + " using " + 80 (toExternalString == null ? "toString()" : "toExternalString()") + 81 ": " + x, x); 82 } 83 } 84 85 public Object fromExternalForm(PersistenceManager pm, Object o) { 86 if (o == null) return null; 87 if (!(o instanceof String )) { 88 throw BindingSupportImpl.getInstance().runtime( 89 "Expected String to create instance of " + 90 type.getName() + ", got: " + Utils.toString(o)); 91 } 92 try { 93 return constructor.newInstance(new Object []{o}); 94 } catch (Throwable x) { 95 throw BindingSupportImpl.getInstance().fatalDatastore( 96 "Unable to create instance of " + 97 type.getName() + " from '" + Utils.toString(o) + "': " + x, x); 98 } 99 } 100 101 public Class getExternalType() { 102 return String .class; 103 } 104 105 public void writeExternal(ObjectOutput out) throws IOException { 106 out.writeObject(type); 107 } 108 109 public void readExternal(ObjectInput in) throws IOException , 110 ClassNotFoundException { 111 type = (Class )in.readObject(); 112 init(); 113 } 114 } 115 116 | Popular Tags |