package jython; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.TreeMap; public class ClassReloader extends ClassLoader { static TreeMap classes = new TreeMap(); public static String dir = "bin"; synchronized public static Class gc(String name) { for (String key : classes.keySet()) { if (key.equals(name)) return classes.get(key); } Class rclass = null; try { rclass = Class.forName(name); } catch (ClassNotFoundException e) { } return rclass; } synchronized public static Class rc(String name) { Class oldclass = gc(name), nclass = null; File file = new File(dir + File.separator + name.replace(".", File.separator) + ".class"); try { if (!file.exists()) { System.out.println("Class wasn't found!"); } byte[] b = new byte[(int) file.length()]; new FileInputStream(file).read(b); nclass = new ClassReloader().defineClass(name, b, 0, (int) file .length()); if (nclass != null) { if (oldclass != null) { for (Field field : nclass.getFields()) { try { if (Modifier.isStatic(field.getModifiers()) && oldclass.getField(field.getName()) != null) field.set(nclass, oldclass.getField( field.getName()).get(oldclass)); } catch (SecurityException e) { } catch (IllegalArgumentException e) { } catch (NoSuchFieldException e) { } catch (IllegalAccessException e) { } } } classes.put(name, nclass); } } catch (FileNotFoundException e) { } catch (IOException e) { } return nclass; } /* public static void main(String[] args) { Class c1 = ClassReloader.gc("jython.My"); for (Field f : c1.getDeclaredFields()) { System.out.println(f.getName()); } //change class file Class c2 = ClassReloader.rc("jython.My"); for (Field f : c2.getDeclaredFields()) { System.out.println(f.getName()); } }*/ }