您可以相对容易地将新代码加载到新的类加载器中:
案例 1:如果您的类在当前上下文中具有公共父接口(或类),例如 Runnable,则可以使用以下代码:
public void doMyClassLogicVersion1() {
ClassLoader loader = URLClassLoader.newInstance(
new URL[] { yourURL1 },
getClass().getClassLoader()
);
Class<?> clazz = Class.forName("mypackage.MyClass", true, loader);
Class<? extends Runnable> runClass = clazz.asSubclass(Runnable.class);
// Avoid Class.newInstance, for it is evil.
Constructor<? extends Runnable> ctor = runClass.getConstructor();
Runnable doRun = ctor.newInstance();
doRun.run();
}
public void doMyClassLogicVersion2() {
ClassLoader loader = URLClassLoader.newInstance(
new URL[] { yourURL2 },
getClass().getClassLoader()
);
Class<?> clazz = Class.forName("mypackage.MyClass", true, loader);
Class<? extends Runnable> runClass = clazz.asSubclass(Runnable.class);
// Avoid Class.newInstance, for it is evil.
Constructor<? extends Runnable> ctor = runClass.getConstructor();
Runnable doRun = ctor.newInstance();
doRun.run();
}
案例 2:如果类不共享一个共同的父级:
public void doMyClassLogicVersion1() {
ClassLoader loader = URLClassLoader.newInstance(
new URL[] { yourURL1 },
getClass().getClassLoader()
);
Class<?> clazz = Class.forName("mypackage.MyClass", true, loader);
// Avoid Class.newInstance, for it is evil.
Constructor<?> ctor = runClass.getConstructor();
Object obj = ctor.newInstance();
String methodName = "getName";
java.lang.reflect.Method method;
try {
method = clazz.getMethod(methodName, param1.class, param2.class, ..);
} catch (SecurityException e) {
// ...
} catch (NoSuchMethodException e) {
// ...
}
try {
method.invoke(obj, arg1, arg2,...);
} catch (IllegalArgumentException e) {
// ...
} catch (IllegalAccessException e) {
// ...
} catch (InvocationTargetException e) {
// ...
}
}
public void doMyClassLogicVersion2() {
ClassLoader loader = URLClassLoader.newInstance(
new URL[] { yourURL2 },
getClass().getClassLoader()
);
Class<?> clazz = Class.forName("mypackage.MyClass", true, loader);
// Avoid Class.newInstance, for it is evil.
Constructor<?> ctor = runClass.getConstructor();
Object obj = ctor.newInstance();
String methodName = "getName";
java.lang.reflect.Method method;
try {
method = clazz.getMethod(methodName, param1.class, param2.class, ..);
} catch (SecurityException e) {
// ...
} catch (NoSuchMethodException e) {
// ...
}
try {
method.invoke(obj, arg1, arg2,...);
} catch (IllegalArgumentException e) {
// ...
} catch (IllegalAccessException e) {
// ...
} catch (InvocationTargetException e) {
// ...
}
}