You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

VersionManager.java 2.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package sample.evolve;
  2. import java.util.Hashtable;
  3. import java.lang.reflect.*;
  4. /**
  5. * Runtime system for class evolution
  6. */
  7. public class VersionManager {
  8. private static Hashtable versionNo = new Hashtable();
  9. public final static String latestVersionField = "_version";
  10. /**
  11. * For updating the definition of class my.X, say:
  12. *
  13. * VersionManager.update("my.X");
  14. */
  15. public static void update(String qualifiedClassname)
  16. throws CannotUpdateException {
  17. try {
  18. Class c = getUpdatedClass(qualifiedClassname);
  19. Field f = c.getField(latestVersionField);
  20. f.set(null, c);
  21. }
  22. catch (ClassNotFoundException e) {
  23. throw new CannotUpdateException("cannot update class: "
  24. + qualifiedClassname);
  25. }
  26. catch (Exception e) {
  27. throw new CannotUpdateException(e);
  28. }
  29. }
  30. private static Class getUpdatedClass(String qualifiedClassname)
  31. throws ClassNotFoundException {
  32. int version;
  33. Object found = versionNo.get(qualifiedClassname);
  34. if (found == null)
  35. version = 0;
  36. else
  37. version = ((Integer)found).intValue() + 1;
  38. Class c = Class.forName(qualifiedClassname + "$$" + version);
  39. versionNo.put(qualifiedClassname, new Integer(version));
  40. return c;
  41. }
  42. /*
  43. * initiaVersion() is used to initialize the _version field of the updatable
  44. * classes.
  45. */
  46. public static Class initialVersion(String[] params) {
  47. try {
  48. return getUpdatedClass(params[0]);
  49. }
  50. catch (ClassNotFoundException e) {
  51. throw new RuntimeException("cannot initialize " + params[0]);
  52. }
  53. }
  54. /**
  55. * make() performs the object creation of the updatable classes. The
  56. * expression "new <updatable class>" is replaced with a call to this
  57. * method.
  58. */
  59. public static Object make(Class clazz, Object[] args) {
  60. Constructor[] constructors = clazz.getConstructors();
  61. int n = constructors.length;
  62. for (int i = 0; i < n; ++i) {
  63. try {
  64. return constructors[i].newInstance(args);
  65. }
  66. catch (IllegalArgumentException e) {
  67. // try again
  68. }
  69. catch (InstantiationException e) {
  70. throw new CannotCreateException(e);
  71. }
  72. catch (IllegalAccessException e) {
  73. throw new CannotCreateException(e);
  74. }
  75. catch (InvocationTargetException e) {
  76. throw new CannotCreateException(e);
  77. }
  78. }
  79. throw new CannotCreateException("no constructor matches");
  80. }
  81. }