Mysterious newInstance method
Posted
by songsungkyun
on Stack Overflow
See other posts from Stack Overflow
or by songsungkyun
Published on 2010-05-07T09:16:26Z
Indexed on
2010/05/07
9:18 UTC
Read the original article
Hit count: 183
java
|reflection
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, not exist 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 know that it's not very important for my life or your life. But it's so mysterisou to me, and my all curiosity. thanks.. ^^
© Stack Overflow or respective owner