1 package sample.evolve; 2 3 import java.util.Hashtable ; 4 import java.lang.reflect.*; 5 import javassist.CtClass; 6 7 10 public class VersionManager { 11 private static Hashtable versionNo = new Hashtable (); 12 public final static String latestVersionField = "_version"; 13 14 19 public static void update(String qualifiedClassname) 20 throws CannotUpdateException 21 { 22 try { 23 Class c = getUpdatedClass(qualifiedClassname); 24 Field f = c.getField(latestVersionField); 25 f.set(null, c); 26 } 27 catch (ClassNotFoundException e) { 28 throw new CannotUpdateException("cannot update class: " 29 + qualifiedClassname); 30 } 31 catch (Exception e) { 32 throw new CannotUpdateException(e); 33 } 34 } 35 36 private static Class getUpdatedClass(String qualifiedClassname) 37 throws ClassNotFoundException 38 { 39 int version; 40 Object found = versionNo.get(qualifiedClassname); 41 if (found == null) 42 version = 0; 43 else 44 version = ((Integer )found).intValue() + 1; 45 46 Class c = Class.forName(qualifiedClassname + '$' + version); 47 versionNo.put(qualifiedClassname, new Integer (version)); 48 return c; 49 } 50 51 54 public static Class initialVersion(String [] params) { 55 try { 56 return getUpdatedClass(params[0]); 57 } 58 catch (ClassNotFoundException e) { 59 throw new RuntimeException ("cannot initialize " + params[0]); 60 } 61 } 62 63 67 public static Object make(Class clazz, Object [] args) { 68 Constructor[] constructors = clazz.getConstructors(); 69 int n = constructors.length; 70 for (int i = 0; i < n; ++i) { 71 try { 72 return constructors[i].newInstance(args); 73 } 74 catch (IllegalArgumentException e) { 75 } 77 catch (InstantiationException e) { 78 throw new CannotCreateException(e); 79 } 80 catch (IllegalAccessException e) { 81 throw new CannotCreateException(e); 82 } 83 catch (InvocationTargetException e) { 84 throw new CannotCreateException(e); 85 } 86 } 87 88 throw new CannotCreateException("no constructor matches"); 89 } 90 } 91 | Popular Tags |