下面的錯誤在google上搜了半天也沒有特別滿意的答案,後來看到一篇關於JUnit類加載器Bug的文章,總算覺得柳暗花明....
java.lang.LinkageError: Class org/w3c/dom/Document violates loader constraints at java.lang.ClassLoader.defineClass0(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:502) at java.lang.ClassLoader.defineClass(ClassLoader.java:431) at ....... |
這樣的異常,主要是由於非系統 類加載器,即自定義的類加載器出現了問題,這個類加載器試圖加載org.w3c.dom.Document ,此時如果類加載器沒有進行正確的處理,或者Document 類不在JVM's system classpath下,類加載器便無法加載,自己加載不了,也不通知系統類加載器,上面的錯誤就出現啦。。。
可能理解有問題,可參照下面這篇文章,我試驗了一下,完全可信:
Here's a patch for JUnit's busted classloader: junit-patch.jar. And below is XmlTest.java, a regression test that breaks (with a java.lang.LinkageError) with the old classloader and the swingui/awtui TestRunners, but passes with the patch. junit-patch.jar contains two classes (source included):
XmlTest.java: import junit.framework.TestCase; import javax.xml.parsers.*; import org.w3c.dom.Document; import org.w3c.dom.Element; public class XmlTest extends TestCase { Document doc = null; public void testXml() throws ParserConfigurationException { doc = DocumentBuilderFactory.newInstance() .newDocumentBuilder() .newDocument(); // System.out.println("Hello! I changed again"); Element root = doc.createElement("xml-test"); assertNotNull(root); } } This is a simple test that reproduces a LinkageError with the JUnit buggy ClassLoader under the following conditions:
You should see this in the runner's error display window: java.lang.LinkageError: Class org/w3c/dom/Document violates loader constraints at java.lang.ClassLoader.defineClass0(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:502) at java.lang.ClassLoader.defineClass(ClassLoader.java:431) at junit.runner.TestCaseClassLoader.loadClass(TestCaseClassLoader.java:104) at java.lang.ClassLoader.loadClass(ClassLoader.java:255) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:315) at XmlTest.testXml(XmlTest.java:16) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at junit.swingui.TestRunner$16.run(TestRunner.java:623) Now run the same test with the fixed ClassLoader:
|