title: Java: Automatic Custom ClassLoader
body: <p>My application uses the Standard Widget Toolkit (SWT) for it's GUI.  My problem is that the 32-bit SWT library does not work on a 64-bit JVM.  But I don't want to make people select the correct architecture when getting the software.  So, I want to bundle <em>both</em> the 32-bit and 64-bit libraries, and auto-detect the architecture during runtime.  I found out I can get the correct architecture of the JVM like so:</p>
  
  <pre><code>if (System.getProperty("os.arch").contains("64")) {
      // ...
  }
  </code></pre>
  
  <p>Now all that's left is to load the jar.  But the problem is, all the examples I found require that you manually load the class before using it.</p>
  
  <pre><code>Class.forName("MyClass", false, myClassLoader);
  </code></pre>
  
  <p>So my question is, is it possible to "register" my class loader, so that I don't have to load classes beforehand?</p>
  
  <hr>
  
  <p><strong>Update:</strong>  I created my own child class of <code>URLClassLoader</code> and set it as the default class loader with the command line argument <code>-Djava.system.class.loader</code>; but I get this error:</p>
  
  <pre><code>Error occurred during initialization of VM
  java.lang.Error: java.lang.NoSuchMethodException: com.program.LibraryLoader.&lt;init&gt;(java.lang.ClassLoader)
      at java.lang.ClassLoader.initSystemClassLoader(Unknown Source)
      at java.lang.ClassLoader.getSystemClassLoader(Unknown Source)
  </code></pre>
  
  <p>I think <code>LibraryLoader.&lt;init&gt;</code> refers to the constructor... but it's there (<code>public LibraryLoader(URI[] urls)</code>).</p>
  
  <hr>
  
  <p><strong>Update 2:</strong> Almost there, the JVM runs now.  I added this constructor to make it work:</p>
  
  <pre><code>public LibraryLoader(ClassLoader classLoader) {
      super(new URL[0], classLoader);
  }
  </code></pre>
  
  <p>But after adding the jars with <code>addPath()</code> (<code>file:lib/jars/swt.jar</code>), it only produces a <code>NoClassDefFoundError</code>.  Yes, I double-checked that the file exists.</p>