I encounter some problems when I replace jar at runtime. I creaded 2 jars all named A.jar
, the jar just contain 1 class named A.class
, the code for A.class
is very simple, the first jar is: System.out.println("before replacement")
, the second jar is: System.out.println("after replacement")
, I want to replace the first jar with the second jar at the runtime, so I put the first jar under C:
and the second jar under C:\test\
my codes are:
import java.lang.reflect.Method;
public class B {
public static void main(String[] args) throws Exception{
final String src = "C:\\test\\A.jar";
final String desc = "C:\\";
System.out.println("start to copy A.jar");
String cmd = "cmd /c xcopy " + src + " " + desc + " /y";
Runtime.getRuntime().exec(cmd).waitFor();
System.out.println("finish to copy A.jar");
Class<?> cls = Class.forName("A");
Object obj = cls.newInstance();
Method m = cls.getMethod("test");
m.invoke(obj, null);
/*A a = new A();
a.test();*/
}
}
I found 2 problems:
- when I run the codes in the eclipse, the result is
"after replacement"
, it's OK. But when I run the same code using command line, it will throwClassNotFoundException
. What's the problem with the command line? In the eclipse when I replace Java reflection codes
Class<?> cls = Class.forName("A"); Object obj = cls.newInstance(); Method m = cls.getMethod("test"); m.invoke(obj, null);
with
A a = new A(); a.test();
the output is
"before replacement"
. I think theA
class should be loaded at the runtime,so whennew A()
the class should be first loaded, at that time the jar has been replaced, why the output still"before replacement"
and jave reflection codes works fine?
Give me some directions please. Thanks!
Add more, I used -verbose:class to print all class load information, I found for class.forname the A.jar is loaded after the replacement finished, whereas for new A() the A.jar is loaded successful between my codes System.out.println("start to copy A.jar") and System.out.println("finish to copy A.jar"). this is cause the result is different. but why the A.jar is loaded before new A()?