在运行时动态加载jar包容易,但是如果想动态替换运行时的类,需要定义自己的classloader , 用自己的classloader 来load这个类。具体代码如下。
public class UClassloader extends URLClassLoader{ public UClassloader(URL[] urls) { super(urls); } public static void main(String args[]) throws IOException, SecurityException, ClassNotFoundException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, InterruptedException{ File f = new File("/Users/fcc/workspace/edm/myclass.jar"); UClassloader u = new UClassloader(new URL[]{f.toURI().toURL()}); Class<?> cs = u.loadClass("org.apache.lucene.demo.classloader.MyClass"); Interface instance = (Interface)cs.newInstance(); instance.say(); u.close(); Thread.sleep(15*1000); UClassloader uAgain = new UClassloader(new URL[]{f.toURI().toURL()}); Constructor<?> csAgain = uAgain.loadClass("org.apache.lucene.demo.classloader.MyClass").getConstructor(); Interface instanceAgain = (Interface)csAgain.newInstance(); instanceAgain.say(); uAgain.close(); }
?