Hi, All.
This question is about the newInstance method and the call of missing classes(libraries) in run time.
First I show some code.
library: axis.jar, dom4j.jar jdk1.5, windowsXP
T.java
import java.io.StringWriter;
import org.apache.axis.utils.StringUtils;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class T {
public T() {
System.out.println("constructor");
}
public void test() {
System.out.println(StringUtils.unescapeNumericChar("1"));
}
public String getPrettyXML(String xml) throws Exception {
System.out.println("getPrettyXML");
StringWriter sw = new StringWriter();
XMLWriter writer = null;
try {
OutputFormat format = OutputFormat.createPrettyPrint();
org.dom4j.Document document = DocumentHelper.parseText(xml);
writer = new XMLWriter(sw, format);
writer.write(document);
} catch (Exception e) {
throw e;
} finally {
if (writer != null) {
try {
writer.close();
} catch (Exception e) {
}
}
}
return sw.toString();
}
public void a() {
System.out.println("a");
}
public static void main(String[] args) {
new T().test();
}
}
T2.java
public class T2 {
public static void main(String[] args) throws Exception {
System.out.println("T2");
T t = (T) Class.forName("T").newInstance();
}
}
Ok, here we go... run as (Of course, I'm run at the directory where T.class, T1.class is)
java T2
as you can see, the command does not have a class path.
==console==
T2
constructor
OK... Now delete
throw e
line at the catch block on the "getPrettyXML" method of T.
Ok, here we go.. run one more time without classpath
java T2
You can see below...
==console==
T2
Exception in thread "main" java.lang.NoClassDefFoundError: org/dom4j/io/OutputFormat
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at T2.main(T2.java:5)
I like to know why the second case is fail. Only just because of "throw e" statement existence.
As far as I know, although the code has a missing classes part, it's OK if a missing classes code part isn't called in runtime. So the second case, because the getPrettyXML method is not yet called and just a default constructor is called by newInstance method, I think the ouput of the second case is same with the first case.
P.S. Here is my eclipse project. http://www.sharefile.org/showfile-2471/classscope.zip